I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!
Related
I'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.
I am trying to update my database table but I have encountered a MySQLSyntaxErrorException. May I know how can I solve this error?
Thanks ! :)
//Retrieve data from database
String queryy = "SELECT agent.agentID, agent.agentEmail, departmentName FROM agent JOIN department ON agentEmail = email";
rs = myStat.executeQuery(queryy);
//Iterate the result set and get one row at a time
while (rs.next()) {
int id = rs.getInt("agentID");
email = rs.getString("agentEmail");
String emaill = email;
departmentName = rs.getString("departmentName");
String departmentNamee = departmentName;
System.out.println("Agent ID = " + id);
System.out.println("Department Name = " + departmentNamee);
System.out.println("Email = " + emaill + newLine);
//Update agentID in department table from agent table
String departmentUpdateSql = "UPDATE department SET agentID = ?"
+ "VALUES ('" + id +"')";
myStat.executeUpdate(departmentUpdateSql);'
And this is the error that I got:
Exception in thread "main" 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 '?VALUES ('23')' at line 1
sql update statements do not use the VALUES keyword (that is for inserts)
Use a PreparedStatement as below
String updateTableSQL = "UPDATE department SET agentID = ?"
PreparedStatement preparedStatement =
dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, id);
// execute update SQL stetement
preparedStatement.executeUpdate();
Note
I would imagine that you would also need some kind of where clause otherwise you will be updating all records
Im trying to add the number 1 to a certain field. How could i manage to do that? Ive tried it but i can never get it to add 1. My ms access table column is set to Number not text.
if (s2.equals(box1Text)) {
if (s3.equals(box2Text)) {
if (s5.equals(currentWinner)) {
String sql = "UPDATE Table2 "+ "SET Score = ? " + "WHERE Better = '" + s1+"'";
PreparedStatement stmt = con.prepareStatement(sql);
//points made here
if (s4.equals(betScore)) {
stmt.setString(1, "+1");//how could i add 1 to the field?
stmt.executeUpdate();
} else {
}
First you do something that is regarded as bad practice : you construct your query by adding the value of a parameter in the string.
String sql = "UPDATE... >+ s1 +<..."
Please nether do that (what is between > and <) when programming seriouly, but allways use ? to pass values.
Second, SQL can do the job for you :
String sql = "UPDATE Table2 SET Score = Score + 1 WHERE Better = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s1);
stmt.executeUpdate();
(try, catch, tests and other details omitted for brevity)
I'm having trouble inserting data inside my database..this is my codes looks like..
rs = stat.executeQuery("Select * from students;");
while (rs.next()) {
idNum = rs.getString("idNum");
stat.executeUpdate(
"INSERT INTO record VALUES (null,'" + idNum + "','" + descript +
"'," + value + ",'" + user.getText() + "','" + timeStamp + "')"
);
}//while
As you can see I want to insert a data for every student rs = stat.executeQuery("Select * from students;"); and get all their student number idNum = rs.getString("idNum"); this is what inside the students table:
idNum..............Name
11000001.........Leonardo
11000002.........David
11000003.........Robert
11000004.........Anna
11000005.........May
now when I get all their idNum I want them to be inserted inside the table record that will looks like this:
idNum.........descript.........amount........blablablabla
11000001.......Fee...............30
11000002.......Fee...............30
11000003.......Fee...............30
11000004.......Fee...............30
11000005.......Fee...............30
the problem is only the first idNum is being inserted inside the table record like this:
idNum.........descript.........amount........blablablabla
11000001.......Fee...............30
You shoulkd not use the same statement object stat twice: once you are reusing is to perform the update (in your case the insert) it closes the resultset you are looping over.
You can use a single statement to copy the data.
(Using parameters avoids formatting problems with strings containing special characters.)
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO record SELECT NULL, idNum, ?, ?, ?, ? FROM students");
ps.setString(1, descript);
ps.setInt (2, value);
ps.setString(3, user.getText());
ps.setString(4, timeStamp);
ps.execute();
Use an ArrayList to store all idNum from students table. Then loop through the list to insert into record table.
I have a sql query which when I manually sends to an Oracle DB through SQLDeveloper Application gets me the output I want. But the same query returns nothing while I try to connect and query through JDBC driver why this is happening so. Please help me.
code:
String sql = "select * from tablename where id='" + id + "' AND case_id = '" + case_id + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
System.out.println("next = " + rs.next());
output:
select * from tablename where id='1' AND case_id = '1000'
next = false
Both connections (JDBC and SQLDeveloper) are using same username and password. So no issue of privilege or security i think.
Try to pass the "id" as a number. As you are passing the ID as String, the JDBC driver will convert it to CHAR, VARCHAR, or LONGVARCHAR.
String sql = "select * from tablename where id=" + id + " AND case_id = '" + case_id + "'";
Resulting string:
select * from tablename where id=1 AND case_id = '1000'
Consider to use PreparedStatement with bind parameters, to avoid sql injection:
String sql = "select * from tablename where id = ? AND case_id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 1);
ps.setString(2, "1000");
ResultSet rs = ps.executeQuery();
References:
http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/mapping.html
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html