我试图在我执行此查询的表格中插入一些值
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)
答案 0 :(得分:4)
'username'
之间,因此您的查询应该如下statement.execute("INSERT INTO "+tableName +" VALUES ('" + userName +"','" + password +"')");
但这不安全,为了避免任何语法错误或SQL Inject,您必须改为使用PreparedStatement。
关于此错误java.sql.SQLSyntaxErrorException
会发生这种情况,因为您没有指定要在查询中插入哪些列,因此它应如下所示:
INSERT INTO tableName(username_col, password_col) VALUES ('userName', 'password') //-----------------------^-------------^----------------------^-----------^