SQL查询不适用于MySQL

时间:2014-12-25 08:06:19

标签: java mysql

我想动态更新数据库中emp表的esal,但查询生成错误

import java.sql.*;
import java.util.*;

class JdbcEx6
{
    public static void main(String args[])throws Exception
    {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        Connection ob = DriverManager.getConnection("jdbc:odbc:mysql1","root","root123");

        Statement st = ob.createStatement();

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the empid");

        int eno = sc.nextInt();

        System.out.println("Enter the increment");

        int inc = sc.nextInt();

        String myquery = "update emp set esal=esal+"+inc+"where eno="+eno;/*error here*/

        int count = st.executeUpdate(myquery);

        ob.close();

        if(count==0)
        System.out.println("Invalid employee Id provided");

        else
        System.out.println("Updated  successfully");


    }
}

/ *手册,对应于您的MySQL服务器版本,以便在' eno = 100'附近使用正确的语法在第1行         at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)

    at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)

    at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)

    at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)

    at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)

    at JdbcEx6.main(a7.java:18)*/

3 个答案:

答案 0 :(得分:2)

正如其他人解释的那样,可以通过在where:

中添加一个空格来解决问题
String myquery = "update emp set esal=esal+" + inc + " where eno="+eno;
//....................................................^ here
int count = st.executeUpdate(myquery);

更好的解决方案是使用PreparedStatement而不是纯字符串连接。这是一个例子:

//query is more readable and easier to understand
//this way is easier to spot problems in the query
//? means a parameter to use in the query
String myquery = "update emp set esal=(esal+?) where eno=?";
//the connection prepares the query
PreparedStatement pstmt = ob.prepareStatement(myquery);
//set the parameters in the PreparedStatement
pstmt.setInt(1, inc);
pstmt.setInt(2, eno);
//execute the statement, which will replace the ? by the parameters
int count = pstmt.executeUpdate();

答案 1 :(得分:1)

String myquery = "update emp set esal=(esal+'"+inc+"') where eno='"+eno"';

这有效

答案 2 :(得分:0)

您的查询中未正确包含空格。 java中的SQL查询需要正确空间,就像在标准SQL使用中一样。