SQLSyntaxErrorException:Column' TEST'要么不在FROM列表中的任何表中,要么出现在连接规范中

时间:2017-04-28 09:44:47

标签: java sql jdbc derby

我试图在我执行此查询的表格中插入一些值

public static final String tableName = "ACCOUNT_TABLE"; 

statement.executeUpdate("CREATE TABLE "+ tableName +" (" +
   " ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY ("+
   " START WITH 1, INCREMENT BY 1), username VARCHAR(15), password VARCHAR(100)" + ")");

在成功创建表之后,我调用register方法将用户插入表

public boolean registerAccount(final User user){
    if (statement != null){
        final String userName = user.getUserName();
        final String password = user.getPassword();
        try {
            return statement.execute("INSERT INTO "+tableName +" VALUES (" + userName +"," + password +")");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return false;
}

在此示例中,userName ==" TEST"和密码==" 123"

此处 return statement.execute("INSERT INTO "+tableName+" VALUES (" + userName +"," + password +")"); 抛出异常

java.sql.SQLSyntaxErrorException: Column 'TEST' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE  statement then 'TEST' is not a column in the target table.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)

1 个答案:

答案 0 :(得分:4)

  1. 字符串应在两个'username'之间,因此您的查询应该如下statement.execute("INSERT INTO "+tableName +" VALUES ('" + userName +"','" + password +"')");
  2. 但这不安全,为了避免任何语法错误或SQL Inject,您必须改为使用PreparedStatement。

  3. 关于此错误java.sql.SQLSyntaxErrorException会发生这种情况,因为您没有指定要在查询中插入哪些列,因此它应如下所示:

  4.     INSERT INTO tableName(username_col, password_col) VALUES ('userName', 'password')
        //-----------------------^-------------^----------------------^-----------^