Jem*_*ili 5 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)" + ")");
Run Code Online (Sandbox Code Playgroud)
之后,当表成功创建时,我正在调用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;
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中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)
Run Code Online (Sandbox Code Playgroud)
'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')
// ----------------------- ^ ------------- ^ ---------- ------------ ^ ----------- ^