简体   繁体   English

Java JDBC 错误插入

[英]Java JDBC Error Insert into

Here is the code:这是代码:

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();
    }

And when I run the code I get this error:当我运行代码时,我收到此错误:

You have an error in your SQL syntax;您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)”附近使用的正确语法

I'm not entirely sure why I get the error so if you know that would be great.我不完全确定为什么我会收到错误,所以如果你知道那会很棒。

order is a reserved word, try order是保留字,试试

String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
            "VALUES (?, ?, ?);";

Your query contains a RESERVED KEYWORD order as your table name.您的查询包含一个RESERVED KEYWORD order作为您的表名。 MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'. MySQL 文档明确建议应始终避免使用此类关键字,如果需要使用它们,则必须使用反引号,如下所示。

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers. MySQL 中的某些对象,包括数据库、表、索引、列、别名、视图、存储过程、分区、表空间和其他对象名称,称为标识符。

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.如果标识符包含特殊字符或者是保留字,则在引用它时必须引用它。

Your query that gets assigned to a String in turn should be changed to the following to resolve this error!依次分配给String查询应更改为以下内容以解决此错误!

"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"

The following is a documentation link to the reserved keywords for MySQL -> Documentation以下是 MySQL 保留关键字的文档链接 ->文档

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM