简体   繁体   English

JDBC插入查询错误

[英]JDBC Insert Query Error

I'm new to Java and JDBC.. Currently I'm working on a school project for a Java course. 我是Java和JDBC的新手。目前,我正在为Java课程从事学校项目。 I'm trying to pass some java variables to an Insert SQL query using JDBC, but I'm getting the follow exception: 我正在尝试使用JDBC将一些Java变量传递给Insert SQL查询,但出现以下异常:

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. 首先,收到错误的原因是您的SQL中存在语法错误。 Simply printing the String you're creating would show you the problem. 简单地打印您正在创建的String将向您显示问题。

That said, you should be using prepared statements . 就是说,您应该使用准备好的语句 THere is simply no reason to construct the SQL manually. 根本没有理由手动构造SQL。 Not only does it avoid the problem you're having, it all but eliminates the chance your code is susceptible to SQL injection. 它不仅避免了您遇到的问题,而且还消除了您的代码容易受到SQL注入的机会。

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 ,因为它在SQL注入中更加容易并且非常强大。

    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+"')"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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