Java Incorrect syntax near '0' - java

I'm having problems trying to insert the values into my database.
When i do the code below it works
insertString = "insert into Players
values(1,'Fred','Fish','fredfish#gamer.net','Ithroeann',19770322)";
statement.executeUpdate(insertString);
but when I try to do this look here it gives me an incorrect syntax near '0' error
I'm trying to loop it to add it automatically through a file
Scanner input = new Scanner(new File("players.txt"));
while (input.hasNext()) {
String[] temp;
String str = input.next();
temp = str.split("\\|");
insertString = "insert into Players values(temp[0], temp[1],temp[2],temp[3],temp[4],temp[5])";
statement.executeUpdate(insertString);
}

This is a String. If you want to append elements of the temp array to the String, you can't do it this way.
You can do it like this :
insertString = "insert into Players values("+temp[0]+",'"+temp[1]+"','"+temp[2]+"','"+temp[3]+"','"+temp[4]+"',"+temp[5]+")";
statement.executeUpdate(insertString);
Of course using a PreparedStatement would be a much better solution.
PreparedStatement stmt = conn.prepareStatement("insert into Players values(?,?,?,?,?,?)");
stmt.setInt (1, Integer.parseInt(temp[0]));
stmt.setString (2, temp[1]);
stmt.setString (3, temp[2]);
stmt.setString (4, temp[3]);
stmt.setString (5, temp[4]);
stmt.setInt (6, Integer.parseInt(temp[5]));
stmt.executeUpdate();

Use a PreparedStatement to bind your query parameters as
PreparedStatement pStmt = connection.prepareStatement(
"insert into Players values (?, ?, ?, ?, ?, ?)");
// index starts from 1
int i = 1;
// bind first int value
pStmt.setInt(i, Integer.parseInt(temp[0]));
// bind string values
for (; i < temp.length; i++)
pStmt.setString(i, temp[i-1]);
// bind last int value
pStmt.setInt(i, Integer.parseInt(temp[i-1]));
// execute insert
pStmt.executeUpdate();

Unless the code posted above is partial, it seems like you're missing the statement preparation part. Try something like the following:
Scanner input = new Scanner(new File("players.txt"));
while (input.hasNext()) {
String[] temp;
String str = input.next();
temp = str.split("\\|");
dbConnection = getDBConnection(); // Implement this method based on your DB configuration
String insertString = "insert into Players values(?, ?, ? , ?, ?, ?)";
PreparedStatement statement = dbConnection.createStatement();
statement.setInt(temp[0]); // int, or whichever type you have
statement.setInt(temp[1]); // int, or whichever type you have
statement.setInt(temp[2]); // int, or whichever type you have
statement.setInt(temp[3]); // int, or whichever type you have
statement.setInt(temp[4]); // int, or whichever type you have
// ^ for the above, if all fields are the same - you can do this in a loop
statement.executeUpdate(insertTableSQL); // execute the insert

Related

How to insert List<String[]> data into database using JDBC?

The current format of my List<String[]> is:
60 52 0 0 1512230400
76 52 1 1 1514044800
42 52 4 1 1516464000
Whereby each separated value by space is a row in my database table, for example: 60 52 0 0 1512230400. I want to insert the 5 separate values per loop. I want to insert all these lines into my database but am not sure on exactly how. This is also a working connection to my database as of now.
This is my rough idea:
String query = "INSERT INTO games (team1_id, team2_id, score1, score2, created_at) VALUES (? ,?, ?, ?, ? )";
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);//prepare the SQL Query
for (String[] s : fixtures) {
}
Any help is amazing.
Many thanks
In your for-loop, you can do something like this:
stmt.setString(1, s[0]); //team1_id if it's of string type in db
stmt.setInt(2, Integer.parseInt(s[1])); //team2_id if it's of type integer in db
stmt.setInt(3, Integer.parseInt(s[2])); //score1
stmt.setInt(4, Integer.parseInt(s[3])); //score2
stmt.setLong(5, Long.parseLong(s[4])); //created_at
stmt.executeUpdate();
The above code shows you how to deal with String, Long and Integer, you can use other types similarly.
List<String[]> fixtures = new ArrayList<>();
fixtures.add(new String [] {"60","52","0","0","1512230400"});
fixtures.add(new String [] {"76","52","1","1","1514044800"});
fixtures.add(new String [] {"42","52","4","1","1516464000"});
String query =
"INSERT INTO games (team1_id, team2_id, score1, score2, created_at)\n"
+ " VALUES (? ,?, ?, ?, ? )";
try(
Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query);
) {
for (String[] s : fixtures) {
stmt.setString(1,s[0]);
stmt.setString(2,s[1]);
stmt.setString(3,s[2]);
stmt.setString(4,s[3]);
stmt.setString(5,s[4]);
stmt.execute();
}
con.commit();
}
With this approach, we pass the bind variables as strings. If needed, based on the actual type of the columns being inserted to, conversion from string (VARCHAR) to numeric (NUMBER) will happen by the database.
You got basically all of it right, but didn't take the next step of actually setting the bind-variables ...
This can work if the input List is already created:
List<String[]> fixtures = ...; // assuming this data is already created
String query = "INSERT INTO games (team1_id, team2_id, score1, score2, created_at) VALUES (? ,?, ?, ?, ? )";
try (Connection con = DBConnector.connect();
PreparedStatement stmt = con.prepareStatement(query)) {
for (String [] row : fixtures) {
// This gets executed for each row insert
for (int i = 0; i < row.length; i++) {
stmt.setInt(i+1, Integer.parseInt(row[i]);
}
stmt.executeUpdate();
}
}
catch(SQLException ex) {
ex.printStackTrace();
// code that handles exception...
}

Java JDBC Error Insert into

Here is the code:
String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
ResultSet keys = null;
try (
PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
){
stmt.setInt(1, 1);
stmt.setInt(2, 3);
stmt.setInt(3, 5);
int affected = stmt.executeUpdate();
if (affected == 1){
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
orderBean.setOrderID(newKey);
}else{
System.out.println("An Error has ocurred while creating the Order.");
}
}catch (SQLException e){
System.err.println(e.getMessage());
}finally{
if (keys != null) keys.close();
}
And when I run the code I get this error:
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 'order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1
I'm not entirely sure why I get the error so if you know that would be great.
order is a reserved word, try
String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
Your query contains a RESERVED KEYWORD order as your table name. MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'.
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
Your query that gets assigned to a String in turn should be changed to the following to resolve this error!
"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"
The following is a documentation link to the reserved keywords for MySQL -> Documentation
Hope this helps!

Insert database mysql get issue

i got issue when i go to Insert value to DB (do nothing).
before that i do select table to get last id, and it worked.
Here's my Code:
IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
Connection connection = null;
int idRoom = params.getInt("idRoom");
String betsmall = params.getUtfString("betsmall");
int Uid = params.getInt("recid");
try{
connection = dbManager.getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT id_game from detail_game ORDER BY id_game DESC LIMIT 1");
ResultSet res = stmt.executeQuery();
if (!res.first())
{
trace("bla bla");
}
int id = res.getInt("id_game");
trace (id);
// **till here there is no problem, i can get id from select query
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
stmts.setInt(1, Uid);
stmts.setInt(2, idRoom);
stmts.setInt(3, id);
stmts.setString(4, betsmall);
stmts.executeUpdate();
}
}
Here's the problem, insert do nothing.
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
Looks like you need some end parentheses in "VALUES".
A catch block to print stack trace would have told you the issue here as well. I'm not the best SQL guy, I always use this to check my SQL syntax as well to double check if I've done everything right.
your connection seems not auto commit. Try to add
stmts.commit();
after "stmts.executeUpdate();".

JBDC batch insert not looping over correctly

I'm currently trying to insert values from a String Array into the three columns within my database
e.g. list 1 into column 1 and so forth. But having issues using the batch insert within the loop. Here is my current code and from what I can gather the only way to do this is by looping over each String Array inserting values unless there is a better way.
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Scores (Home, Score, Away) VALUES (?, ?, ?)");
String[] List1str = new String[List1.size()];
List1str = List1.toArray(List1str);
String[] List2str = new String[List2.size()];
List2str = List2.toArray(List2str);
String[] List3str = new String[List3.size()];
List3str = List3.toArray(List3str);
for (String s1 : List1str) {
stmt.setString(1, s1);
for (String s2 : List2str) {
stmt.setString(2, s2);
for (String s3 : List3str) {
stmt.setString(3, s3);
stmt.addBatch();
}
}
}
stmt.executeBatch();
You should bind all strings before do addBatch().
Currently your addBatch() in last nested loop.
If we take in assumption that all lists has same size, your code should be following:
for (int i=0; i<List1.size(); i++) {
stmt.setString(1, List1[i]);
stmt.setString(2, List2[i]);
stmt.setString(3, List3[i]);
stmt.addBatch();
}
stmt.executeBatch();

Getting index of inserted rows from a MySQL database

I'm using Java (jdbc) to interact with a MySQL database. I have table with a primary index which is AUTO INCREMENT. When I insert a row, I need to get the index it just received. How do I do that?
From: http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-last-insert-id
stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')",
Statement.RETURN_GENERATED_KEYS);
//
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
//
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
// throw an exception from here
}
rs.close();
rs = null;
Thanks to John Boker for his excellent response.
If you wish to use a PreparedStatement, you can still use RETURN_GENERATED_KEYS, but you have to apply the commands differently:
PreparedStatement ps = mysql.prepareStatement(
"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)",
Statement.RETURN_GENERATED_KEYS );
ps.setString(1, "My text");
ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()););
ps.setInt(3, 5150);
ps.executeUpdate();
ResultSet results = ps.getGeneratedKeys();
results.next(); // Assume just one auto-generated key; otherwise, use a while loop here
System.out.println(results.getInt(1)); // there should only be 1 column in your results: the value of the auto-generated key
Add the RETURN_GENERATED_KEYS param in the prepareStatement()
function.
Get results not from statement.executeUpdate() but from
statement.getGeneratedKeys().
Alternatively, using Spring JDBC it would look like:
Map<String, Object> map = new HashMap<String, Object>();
map.put("column1", "test");
map.put("column2", Boolean.TRUE);
SimpleJdbcInsert insert = new SimpleJdbcInsert(template).withTableName("table").usingGeneratedKeyColumns("id");
int id = insert.executeAndReturnKey(map).intValue();

Categories