Java JDBC错误插入到
代码如下:Java JDBC错误插入到,java,mysql,jdbc,insert-into,Java,Mysql,Jdbc,Insert Into,代码如下: String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+ "VALUES (?, ?, ?);"; ResultSet keys = null; try ( PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GEN
String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
ResultSet keys = null;
try (
PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
){
stmt.setInt(1, 1);
stmt.setInt(2, 3);
stmt.setInt(3, 5);
int affected = stmt.executeUpdate();
if (affected == 1){
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
orderBean.setOrderID(newKey);
}else{
System.out.println("An Error has ocurred while creating the Order.");
}
}catch (SQLException e){
System.err.println(e.getMessage());
}finally{
if (keys != null) keys.close();
}
当我运行代码时,会出现以下错误:
您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以了解在第1行的“order orderedBy、totalItems、totalPrice值1、3、5”附近使用的正确语法
我不完全确定为什么会出现错误,所以如果您知道这会很好。顺序是一个保留字,请尝试
String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
查询包含一个保留关键字order作为表名。MySQL文档清楚地表明,应该始终避免使用这些关键字,如果需要使用这些关键字,则必须使用backticks,如下所示
MySQL中的某些对象(包括数据库、表、索引、列、别名、视图、存储过程、分区、表空间和其他对象名)称为标识符
如果标识符包含特殊字符或是保留字,则无论何时引用它,都必须对其进行引用
您依次分配给字符串的查询应更改为以下内容以解决此错误
"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"
以下是MySQL保留关键字的文档链接->
希望这有帮助 我想你已经明白了