简体   繁体   中英

JDBC Insert Query Error

I'm new to Java and JDBC.. Currently I'm working on a school project for a Java course. I'm trying to pass some java variables to an Insert SQL query using JDBC, but I'm getting the follow exception:

SQLException: ORA-00917: missing comma

This is the instruction:

stmt.executeUpdate("INSERT INTO question (idnum, question, option1, option2, option3, option4, answer) VALUES("+4+", "+question+", "+option1+", "+option2+", "+option3+", "+option4+", "+answer+")");

Any ideas how to fix the query?

Try this

String sql = 
   "INSERT INTO question (idnum, question, option1, option2, option3, option4, answer)       VALUES(?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setInt(1, 4);
preparedStatement.setString(2, question);
preparedStatement.setString(3, option1);
preparedStatement.setString(4, option2);
preparedStatement.setString(5, option3);
preparedStatement.setString(6, option4);
preparedStatement.setString(7, answer);

int rowsAffected = preparedStatement.executeUpdate();

First, the reason you are receiving an error is that you have a syntax error in your SQL. Simply printing the String you're creating would show you the problem.

That said, you should be using prepared statements . THere is simply no reason to construct the SQL manually. Not only does it avoid the problem you're having, it all but eliminates the chance your code is susceptible to SQL injection.

String query = "INSERT INTO question (idnum, question, option1, option2, option3, option4, answer) VALUES (?,?,?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1,4);
pstmt.setString(2,question);
// ... set all your params
pstmt.execute();

Change the double quotation " to to a single quote ' like this

String query = "INSERT INTO question (idnum,question) values 
 (4 , "'"+question+"'")";

Note that only string needs ' , you can pass integers directly without using ' , however, I prefer to use PreparedStatement , as it's much easier and very strong with SQL injections.

    PreparedStatement pr = conection.prepareStatement("insert into question(...) values(?,?,?,?...)");
    pr.setInt(1,4);
    pr.setString(2,"Some string");
//.....
 pr.executeUpdate();

尝试这个:

 stmt.executeUpdate("INSERT INTO question (idnum, question, option1, option2, option3, option4, answer) VALUES("+4+", '"+question+"', '"+option1+"', '"+option2+"', '"+option3+"', '"+option4+"', '"+answer+"')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM