ORA-00917:缺少逗号 - 插入查询失败

时间:2016-02-07 12:28:06

标签: java sql oracle jsp jdbc

我试图在JSP页面中创建插入查询,如下所示

index.html

try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { connection = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:" + "XE", "hr","hr"); if (connection != null) { statement = connection.createStatement(); String q2 = "INSERT INTO HR.tweets ("; q2 = q2 + "DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER)"; q2 = q2 + "VALUES ("; q2 = q2 + "(select SYSDATE from dual),"; q2 = q2 + "'" + tweet.getUser().getScreenName() + "'" + ","; q2 = q2 + "'" + tweet.getText() + "'" +","; q2 = q2 + "'" + finalstring + "')"; statement.execute(q2); statement.close(); connection.close(); } } catch (SQLException e) { e.printStackTrace(); } statement.execute(q2)

在代码中创建以下查询:

ORA-00917: missing comma error

请帮帮我。

4 个答案:

答案 0 :(得分:1)

您的SQL插入语法有错误,因为您的某个参数包含'

'hugotinhinyero turn back time good days. mama sing sleep we're stress out. engin'

要避免此类错误,请不要手动构建SQL字符串,而是使用PreparedStatement和参数:

String insert = "INSERT INTO HR.tweets (DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER) " + 
" VALUES ((select SYSDATE from dual),?,?,?)";
PreparedStatement stmt = connection.prepareStatement(insert);
stmt.setParameter(1, tweet.getUser().getScreenName());
stmt.setParameter(2, tweet.getText());
stmt.setParameter(3, finalstring);
stmt.executUpdate();

答案 1 :(得分:0)

这里的问题是您使用的是特殊字符,这会导致发送到数据库的语句无效。

尝试使用这样的预处理语句......

PreparedStatement pstatement = null;
Connection connection = null;
    try 
    {

        connection = DriverManager.getConnection(
        "jdbc:oracle:thin:@localhost:1521:" + "XE", "hr","hr");

        if (connection != null) 
        {
            pstatement = connection.prepareStatement("INSERT INTO HR.tweets (DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER) VALUES ((select SYSDATE from dual),?,?,?)");


            q2 = q2 + "'" + tweet.getUser().getScreenName() + "'" + ",";
            q2 = q2 + "'" + tweet.getText() + "'" +",";
            q2 = q2 + "'" + finalstring + "')";
            pstatement.setString(1, tweet.getUser().getScreenName());
            pstatement.setString(2,tweet.getText());
            pstatement.setString(3, finalstring);
            pstatement.execute();   

        }
    } 
    catch (SQLException e) 
    {
       e.printStackTrace();
    }finally{
        pstatement.close();
        connection.close();
    }

...准备好的语句通常会处理格式错误的字符串和发送给DB的无效引号。

答案 2 :(得分:0)

使用forkJoin代替PreparedStatement 如果您的任何字段包含引号字符(Statement),则查询将始终失败 此外,您的查询易受SQL注入攻击,而PreparedStatement可防范此类攻击。

有关PreparedStatement的详细信息,请参阅本教程:
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
这是一个非常基础的知识,所以我不在这里解释。

答案 3 :(得分:0)

如@wero所述,查询的问题是它包含引号(')。要转义它,您可以使用backslash(\)。

Eg: we\'re

然而,正如其他人所建议的那样,使用prepared-statements更安全,它也可以防止sql注入作为奖励!