MySQL syntax error using Java in Eclipse - java

I have the following prepared statement for sql in Java :
com.mysql.jdbc.JDBC4PreparedStatement#6e56103e:
INSERT INTO `game` (Id , GameStart ,Name, Lenght, MapVersion, Mode)VALUES(2502591,'2000-03-02 02:02:02','5x5 aptb wdw','00:55:48','DotA v6.75b.w3x','aptb ')ON DUPLICATE KEY UPDATE `Id`=VALUES(Id),`GameStart` = VALUES(GameStart),`Name`=VALUES(Name),`Lenght`=VALUES(Lenght),`MapVersion`=VALUES(MapVersion),`Mode`=VALUES(Mode).
When I execute it in Eclipse I get the following 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 '?,?,?,?,?,?)ON DUPLICATE KEY UPDATE `Id`=VALUES(Id),`GameStart` = VALUES(GameSta' at line 1.
But at the same time when I execute the same query in SQLyog I don't get an error. Rows are updated. What can be a problem? Thanks in advance
Code:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dota","root","root");
PreparedStatement updateGame = null;
String updatingGame = "INSERT INTO `game` (Id , GameStart ,Name, Lenght, MapVersion, Mode)" +
"VALUES(?,?,?,?,?,?)" +
"ON DUPLICATE KEY UPDATE " +
"`Id`=VALUES(Id),"+
"`GameStart` = VALUES(GameStart)," +
"`Name`=VALUES(Name)," +
"`Lenght`=VALUES(Lenght)," +
"`MapVersion`=VALUES(MapVersion)," +
"`Mode`=VALUES(Mode)";
con.setAutoCommit(false);
updateGame=con.prepareStatement(updatingGame);
updateGame.setInt(1, game.Id);
Timestamp timestamp = new Timestamp(100,2,2,2,2,2,2);
updateGame.setTimestamp(2,timestamp);
updateGame.setString(3, game.GameName);
updateGame.setTime(4, (Time) game.Time);
updateGame.setString(5, game.MapVersion);
updateGame.setString(6, game.Mode);
updateGame.executeUpdate(updatingGame);
And on:
updateGame.executeUpdate(updatingGame);
I get an error

Firstly if you are using a preparedStatement you have to do it this way
String query="Insert into tablename (col1, col2) values(?,?)";
PreparedStatement stmnt = //get the statement
stmnt.setString(1, "col1val");
stmnt.setString(2, "col2val");

You are inserting a duplicate value on the primary key.
Follow the #chaitanya10 suggestion, use PreparedStatement
How is your knowledge about Object Orientation? As I can see you aren't using correctly encapsulation.

Found my mistake. I should use only executeUpdate() instead of executeUpdate(updatingGame) ;, because if I use it with parameter, I will overwrite values whiten by
updateGame.setInt(1, game.Id);
Timestamp timestamp = new Timestamp(100,2,2,2,2,2,2);
updateGame.setTimestamp(2,timestamp);
updateGame.setString(3, game.GameName);
updateGame.setTime(4, (Time) game.Time);
updateGame.setString(5, game.MapVersion);
updateGame.setString(6, game.Mode);

Related

Working on this Java project where I need to be able to delete data from the database on user's request

The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: 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 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);

How to insert a row into database?

I have written this code to add stuff to the database, however, when I try running it it does not work, i've been looking for ways to do it, but i just cant seem to find the solution, can anyone help?
String mySQL ="INSERT INTO Measurement (Level, Time, Date, TankID)"+"VALUES (textField1, currentTime,currentDate,(SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
stmt.executeUpdate(mySQL);
Both your SQL and prepared statement are malformed. Try using an INSERT INTO ... SELECT here:
String sql = "INSERT INTO Measurement (Level, Time, Date, TankID) ";
sql += "SELECT ?, ?, ?, TankID ";
sql += "FROM Tanks ";
sql += "WHERE TankName = '2' AND Site_ID = '1'";
stmt.setString(1, textField1);
stmt.setString(2, currentTime); // not sure about the type here
stmt.setString(3, currentDate); // also not sure about the type
stmt.executeUpdate();
Note that I am unsure about both the Java and SQL binding types of the columns for currentTime and currentDate. If not string, then the above would have to change slightly.
You should be using PreparedStatement to properly set the first parameter of the insert query and check the documentation of your DB server to use existing functions to get current time and date.
For example, mySQL has functions CURDATE() and CURTIME()
String query = "INSERT INTO Measurement (Level, Time, Date, TankID) "
+ "VALUES (?, CURTIME(), CURDATE(), (SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, textField1); // could be textField1.getText() or textField1.getValue()
statement.executeUpdate();
}
Based on your Database type change the connection details
Follow this Link for creating JDBC Connection and Inserting data
If you did the above steps please ignore this..

Java MySQL UPDATE error using WHERE in conjunction with AND

I am trying to UPDATE an entry in MySQL, the structure of the table is table_rankings (ip text, field text, rank double). Where ip is a user's IP address, field is an object being ranked and rank is the numerical rank of a field. My statement is:
//String for query
String query = "UPDATE "+catagory+"_rankings SET rank = ? WHERE ip = ? AND field = ? )";
PreparedStatement ps = conn.prepareStatement(query);
//fill ? variables
ps.setDouble(1, r[i]);
ps.setString(2, user);
ps.setString(3, s[i]);
ps.executeUpdate();
In this code catagory refers to a given table, for instance baseball_rankings or basketball_rankings. The error I am receiving is:
SQLException: 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
SQLState: 42000
VendorError: 1064
Is the issue that I cannot use WHERE as well as AND in an UPDATE statement? I am also curious if my update is subject to a SQL injection attack because I am using catagory+"_rankings". I have tried to use a ? variable however it results in another error.
you add a extra “)”, or can say, you missed a "(".
try
String query = "UPDATE "+catagory+"_rankings SET rank = ? WHERE ip = ? AND field = ? ";

Returning clause fails (postgres 9.3, jdbc)

I have looked at several link to retrieve the id with an insert using java, and I thought I would use the RETURNING clause.
my code:
Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory", "postgres","root");
String sql = "INSERT INTO main (nom_fichier, adate, mdate, cdate, size, chunknumber)"
+ " VALUES ('test',450,450,450,450,5)"
+ " Returning id"
+ ";";
Statement stmt = c.createStatement();
int rowNumber = stmt.executeUpdate(sql);
But I get this error:
Exception in thread "main" org.postgresql.util.PSQLException: a result was returned when none was expected.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:339)
at fr.infotel.postgre.TestPostgre.main(TestPostgre.java:25)
I also tried to use the Statement.RETURN_GENERATED_KEYS (withouth Returning clause) without success (I had nothing in the result set).
First Question: I would like to make the RETURNING statement work, as my request works in psql
Second Question: If the first is not possible, how can I have the same result
I am using postgres 9.3 with the postgres9.3.jdbc3 jar.
Thanks for your help.
Use ResultSet object instead of rowNumber
ResultSet resultSet = stmt.executeQuery(sql);
your query result now in resultSet variable.

Autoincrement issue - best way to add entries to the database and display them at the same time

I use a SQLite Database and a Java GUI. The information entered on the GUI will be added to a table in the database. This table contains an autoincrement. On the same time I want to display the information on the GUI and change it later.
creating the database:
stat.executeUpdate("create table t1(ROWID INTEGER PRIMARY KEY AUTOINCREMENT, Value);";
adding values to the database:
Statement stat = con.createStatement();
String sql = "insert into t1 values ($next_id,'"+value+');";
stat.executeUpdate(sql);
How can I save the ID in my program so that it will be the same as in the database and I have easy access to my database?
Edit:
I tried the solution mentioned in the comments and run into a NYI exception ...
String sql = "insert into t1 values($next_id,'"+value+"');";
PreparedStatement stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet res = stmt.getGeneratedKeys();
while (res.next()){
int id = res.getInt(1);
System.out.println(id);
}
con.commit();
tried also the solution of Russel and got another exception ("not implemented by SQLite JDBC driver"):
String sql = "insert into t1 values($next_id,'"+value+"');";
Statement stat = con.createStatement();
stat.executeUpdate(sql);
stat.executeUpdate("SELECT LAST_INSERT_ROWID() from t1;", Statement.RETURN_GENERATED_KEYS);
ResultSet res = stat.getGeneratedKeys();
while (res.next()){
int id = res.getInt(1);
System.out.println(id);
}
What did I wrong?
What about just calling SELECT LAST_INSERT_ID()? This returns the last auto-increment value generated for your connection (not affected by other clients' actions).
Alternately, looking at the Javadoc, it seems you should be able to do this with an ordinary Statement:
stat.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keys = stat.getGeneratedKeys();
If you don't mind using an ORM library, try sormula. It will do all of the work for identity column for you. All that is required is #Column(identity=true) annotation on the POJO field that is to be auto incremented.
The test cases in org.sormula.tests.identity package shows you how. Sqlite test set up and sqlitejdbc-v056.jar jar is included. Change build.properties to run db.dir=sqlitejdbc.

Categories

Resources