在Sql查询中获取语法错误

时间:2015-12-30 09:17:23

标签: java mysql jdbc syntax-error

大家好我想尝试将用户输入id与db id进行比较但是 我执行查询我得到语法错误我做错了什么?

 sql = "SELECT individual.id " 
                + "FROM individual"
                + "WHERE individual.id = ? ";
       PreparedStatement pst = con.prepareStatement(sql);
       pst.setInt(1, input);

    while(rs.next()){
        int Iid = rs.getInt("id");
        System.out.println(Iid);
    }

错误消息

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 '.id = ?' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2738)
    at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1617)

1 个答案:

答案 0 :(得分:4)

+ "FROM individual" + "WHERE individ

将解决

  FROM individualWHERE individ...

为你的字符串添加空格,你应该没问题