Dynamically update query in MySQL in Java [duplicate] - java

I just trying to use a update in my application, but i just can't. A the console, this mysql command works, but here, doesn't.
Well, I use this in my program:
conexao = poolMySQL.connect();
final String sql = "UPDATE professor SET codlocal = ? WHERE codprof = ?";
pstmt = conexao.prepareStatement(sql);
pstmt.setInt(1, local);
pstmt.setInt(2, id);
try {
pstmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(ProfessorDAO.class.getName()).log(Level.SEVERE, null, ex);
}
Just reminding, codlocal is a foreign key from another table, named Localidade. I saw some examples about join, but i just can't imagine how this can work for me.
And I get this:
Grave: null
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? WHERE codprof = ?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583)
at DAO.ProfessorDAO.atualizaLocalidade(ProfessorDAO.java:153)
at DAO.Main.main(Main.java:23)
So, what can I do?

You have to use pstmt.executeUpdate(); in place of pstmt.executeUpdate(sql);

Related

Adding new values to mysql database no longer possible?

Hi guys please consider the code below. I was using it to add new values to my table(booking) in mysql database(seat_booking).
Variables include String(id,cname,ctype,event_name) and int(seatsno).I also call a function EventName() in this code and, trust me guys it works perfectly and I am able to derive the event name from the another table(events) but the only problem arises in this method.
Guys my project is to make a seat booking GUI app so this code does work when I used it to add new events for the "Admin" mode but doesn't work here ,i.e., when I need it to store the booking values for a particular customer. Please help guys. I would really appreciate it.
private void newbookbtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/seat_booking","root","<mypassword>");
Statement stmt = con.createStatement();
String query = "SELECT * FROM booking";
ResultSet rs = stmt.executeQuery(query);
String cname = tfcname.getText();
int seatsno = Integer.parseInt(tfseatsno.getText());
String evtname = EventName();
String ctype = "Normal Customer"; long bookid = getID();
String id = Long.toString(bookid);
String query1="insert into booking values('"+ id +"','"+ cname +"','"+ ctype +"','"+evtname+"',"+ seatsno+");";
stmt.executeUpdate(query1);
JOptionPane.showMessageDialog(null, "Booking successfull!");
stmt.close();
con.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Error encountered while booking new event!");
}
}
I have tried putting the e.Stacktrace(); statement in the application and I ran it the following was the resulting output for error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Track Events Warm-up,1)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1816)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1730)
at CustomerNewBook.newbookbtnActionPerformed(CustomerNewBook.java:256)
at CustomerNewBook.access$100(CustomerNewBook.java:16)
at CustomerNewBook$2.actionPerformed(CustomerNewBook.java:110)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
...
You use the wrong driver class. correct is:
Class.forName("com.mysql.jdbc.Driver");
java.sql.Driver is only an Interface. For more informations see the javadoc
BTW: Learn about prepared Statements to prevent sqlinjection
Do not supress error Messages. Atleast log them or put it into the message Dialog:
catch (Exception e)
{
e.printStacktrace();
JOptionPane.showMessageDialog(null,"Error encountered while booking new event!"+e.getMessage());
}
Update 2 (for this comment) :
Check the error,
You have an error in your SQL syntax ... near s Track Events Warm-up,1) ...
The problem is with the Strings that you are passing. Make sure any of your variables (id, cname, ctype, evtname) doesn't contain single qoutes(') or any other escape characters which may disturb the query.
This problem would easily be solved by using Prepared Statements. Try,
String query1 = "INSERT INTO `booking` VALUES(?, ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(query1);
stmt.setString(1, id); //1 specifies the first parameter in the query
stmt.setString(2, cname);
stmt.setString(3, ctype);
stmt.setString(4, evtname);
stmt.setInt(5, seatsno); //use setInt() to parse ints
stmt.executeUpdate();
Update (for this comment):
In your catch block, comment the JOptionPane line and add the following,
catch (Exception e){
e.printStackTrace();
// JOptionPane.showMessageDialog(null, ...);
}
then run your application once again and update the question with the error output.
Original answer :
If you are using jdbc:mysql you need the MySQL connector.
Download it from mysql-connector-java-8.0.12,
Add the mysql-connector-java-8.0.12.jar to your project.
Change the driver class,
Class.forName("com.mysql.jdbc.Driver");
Clean and build (Optional but recommended).

How to extract Object[] and get it into query using preparedstatement setObject()? [duplicate]

This question already has answers here:
PreparedStatement IN clause alternatives?
(33 answers)
Closed 7 years ago.
might be a silly question but I cant get the query running. This is my code:
ArrayList<Attraction> getAttraction(Object[] obj) throws SQLException
{
Connection connection = facade.getConnection();
ArrayList<Attraction> attractions = new ArrayList<>();
// Check obj value
System.out.println(java.util.Arrays.toString(obj));
PreparedStatement ps = connection.prepareStatement("SELECT DISTINCT attra.attractid,attractname,x,y,z,age,weight,"
+ "height,duration,price,status FROM attraction attra "
+ "INNER JOIN attrib_bridge ab ON attra.attractId = ab.attractId "
+ "INNER JOIN attribute attri ON ab.attributeId = attri.attributeid"
+ "WHERE attri.attributename IN ?");
ps.setString(1, java.util.Arrays.toString(obj));
ResultSet rs = ps.executeQuery();
while(rs.next()){
// Initialize attraction object
Attraction attraction = new Attraction();
attraction.setAttractionId(rs.getInt(1));
attraction.setAttractionName(rs.getString(2));
attraction.setxLocation(rs.getInt(3));
attraction.setyLocation(rs.getInt(4));
attraction.setzLocation(rs.getInt(5));
attraction.setMinAge(rs.getInt(6));
attraction.setMaxWeight(rs.getInt(7));
attraction.setMinHeight(rs.getInt(8));
attraction.setRideDuration(rs.getInt(9));
attraction.setPriceRide(rs.getInt(10));
attraction.setStatus(rs.getString(11));
// Add new object to to movies
attractions.add(attraction);
}
return attractions;
}
And this is the error I get :
[Gentle rides, Thrill rides, Transport rides]
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in >your SQL syntax; check the manual that corresponds to your MySQL server version >for the right syntax to use near 'attri.attributename IN '[Gentle rides, Thrill >rides, Transport rides]'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at com.ThemeParkG02.rs.control.manager.ManageAttraction.getAttraction(ManageAttraction.java:123)
at com.ThemeParkG02.rs.control.manager.Facade.getAttraction(Facade.java:85)
at com.ThemeParkG02.rs.control.listener.ViewAttractionListListener.run(ViewAttractionListListener.java:32)
I'm really dizzy right now. The values is out but I the query is not working. The '[' and ']' really blocking my goal. Any input guys?
Thanks in advance.
Note: I missed the issue of the IN clause, but my answer is technically correct, as the first error in the SQL is the missing space. The link provided by Miljen Mikic explains how to fix the IN clause issue.
Your error says:
MySQLSyntaxErrorException: You have an error in >your SQL syntax
You are missing a space before WHERE.
Updated
For improved readability, I prefer writing it like this:
String sql = "SELECT DISTINCT attra.attractid, attractname, x, y, z, age" +
", weight, height, duration, price, status" +
" FROM attraction attra" +
" JOIN attrib_bridge ab ON attra.attractId = ab.attractId" +
" JOIN attribute attri ON ab.attributeId = attri.attributeid" +
" WHERE attri.attributename IN ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, Arrays.toString(obj));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
// Process row here
}
}
}

insert query with varchar as data type for primary key

The program is not accepting the query given below-
public class loginDaos {
public void create(loginBean bean) {
ConnectionPool c = ConnectionPool.getInstance();
c.initialize();
Connection con = c.getConnection();
try {
String sql = "INSERT INTO login VALUES(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, bean.getCode());
pstmt.setString(2, bean.getUserid());
pstmt.setString(3, bean.getPassword());
pstmt.setString(4, bean.getPosition());
pstmt.executeUpdate(sql);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
loginDaos ld = new loginDaos();
loginBean lb = new loginBean("representative", "rep7", "rep7", "r");
ld.create(lb);
}
}
The table is:
CREATE TABLE login
( userid char(25);
password varchar(45),
code char(5),
position char(),
PRIMARY KEY (code)
);
I have currently kept the value of userid,password, code and position as String.The stack trace is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?,?)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1564)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1485)
at login.loginDaos.create(loginDaos.java:33)
at login.loginDaos.main(loginDaos.java:42)
BUILD SUCCESSFUL (total time: 0 seconds)
Help!
When you are using a PreparedStatement, then you should use the executeQuery(), executeUpdate() or execute() method that does not take a String parameter.
So to fix the problem use:
// ....
pstmt.setString(3, bean.getPassword());
pstmt.setString(4, bean.getPosition());
pstmt.executeUpdate();
The MySQL driver implementation has a bug, because the JDBC specification states that the methods accepting a string should throw an SQLException when called on a PreparedStatement or CallableStatement implementation. In this case it only throws the exception because it tries to execute the parametrized query directly.

mysql prepared statement java

I'm working with a prepared statement I've generated, and I'm getting a syntax error on the statement thrown by java. Yet when i copy and paste the toString of the PS into phpmyadmin for the database, it executes flawlessly. any idea's what could be wrong, i'm fairly stumped?
edit: changed to ps.executeUpdate(query); still doesn't work.
public int addOrder(Order order){
int rs=false;
try {
String query = "INSERT INTO `orders`(`orderNumber`, `productNumber`, `quantity`, `orderer`, `assembler`, "
+ "`meshType`, `beadType`, `beadCount`, `notes`, `dateCompleted`, `dateSubmitted`, `isComplete`) "
+"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, order.getOrderNumber());
ps.setInt(2, order.getProductNumber());
ps.setInt(3, order.getQuantity());
ps.setString(4, order.getOrderer());
ps.setString(5, order.getAssembler());
ps.setString(6, order.getMesh());
ps.setString(7, order.getBeadType());
ps.setInt(8, order.getBeadCount());
ps.setString(9, order.getNotes());
ps.setLong(10, order.getDateCompleted().getTime());
ps.setLong(11, order.getDateSubmitted().getTime());
ps.setBoolean(12, order.getIsComplete());
System.out.println(ps.toString());
rs = ps.executeUpdate(query);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
the error message i get, preceded by the ps.toString() from addOrder. and like i said, if i copy paste the relevant part of the toString into phpmyadmin and execute it works fine. any ideas of what i'm doing wrong?
com.mysql.jdbc.JDBC4PreparedStatement#40378309: INSERT INTO
`orders`(`orderNumber`, `productNumber`, `quantity`, `orderer`,
`assembler`, `meshType`, `beadType`, `beadCount`, `notes`,
`dateCompleted`, `dateSubmitted`, `isComplete`) VALUES
('',251,1,'Mark','','Other','LBB',150,'this is a
test',1357249393009,1357249393010,0)
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'?,?,?,?,?,?,?,?,?,?,?,?)' at line 1 at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
Source) at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Source) at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at
com.mysql.jdbc.Util.getInstance(Util.java:386) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2728) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2678) at
com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:894) at
com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:732) at
cbs.business.internalorders.Database.addOrder(Database.java:232) at
cbs.business.internalorders.IOGui$1.widgetSelected(IOGui.java:205) at
org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source) at
org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source) at
org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source) at
org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source) at
org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source) at
cbs.business.internalorders.IOGui.(IOGui.java:218) at
cbs.business.internalorders.InternalOrders.main(InternalOrders.java:15)
#TheCapn's deleted answer is almost correct. Change executeQuery(query) to executeUpdate(), without the parameter.
If you put query in it, it will execute twice. With your case, you should not put query in it. All you need is like this;
ps.executeUpdate(query); <-- remove 'query'
//should be like this
ps.executeUpdate();
executeQuery(); //Generally this use for select statement. The output will be in Resultset.
executeUpdate(); //Generally this use for insert, update, delete and drop table.
execute(); //If you don't know which method to be used for executing your SQL statements, you can use this.
String query = "INSERT INTO `orders`(`orderNumber`, `productNumber`, `quantity`, `orderer`, `assembler`, "
+ "`meshType`, `beadType`, `beadCount`, `notes`, `dateCompleted`, `dateSubmitted`, `isComplete`) "
+"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
should read
String query = "INSERT INTO orders(orderNumber, productNumber, quantity, orderer, assembler, "
+ "meshType, beadType, beadCount, notes, dateCompleted, dateSubmitted, isComplete) "
+"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
i.e. no quotes.
I think the error could be from the data type conversion. Can you try without using parameters and setting the values directly? I had similar issues in ADO.NET before.
I finally found my solution, For some reason it didn't like my setStrings so I set it the long way and got it to work. thank you!

MySQL Java Update Syntax

I just trying to use a update in my application, but i just can't. A the console, this mysql command works, but here, doesn't.
Well, I use this in my program:
conexao = poolMySQL.connect();
final String sql = "UPDATE professor SET codlocal = ? WHERE codprof = ?";
pstmt = conexao.prepareStatement(sql);
pstmt.setInt(1, local);
pstmt.setInt(2, id);
try {
pstmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(ProfessorDAO.class.getName()).log(Level.SEVERE, null, ex);
}
Just reminding, codlocal is a foreign key from another table, named Localidade. I saw some examples about join, but i just can't imagine how this can work for me.
And I get this:
Grave: null
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? WHERE codprof = ?' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583)
at DAO.ProfessorDAO.atualizaLocalidade(ProfessorDAO.java:153)
at DAO.Main.main(Main.java:23)
So, what can I do?
You have to use pstmt.executeUpdate(); in place of pstmt.executeUpdate(sql);

Categories

Resources