【问题标题】:Java JDBC Error Insert intoJava JDBC 错误插入
【发布时间】:2018-07-29 00:15:37
【问题描述】:

代码如下:

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) VALUES (1, 3, 5)" 附近使用正确的语法

我不完全确定我为什么会收到错误,所以如果你知道那会很棒。

【问题讨论】:

  • 我想你已经明白了

标签: java mysql jdbc insert-into


【解决方案1】:

order是保留字,试试看

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

【讨论】:

    【解决方案2】:

    您的查询包含 RESERVED KEYWORD order 作为您的表名。 MySQL 文档明确建议应始终避免使用此类关键字,如果需要使用它们,则必须使用反引号,如下所示。

    MySQL 中的某些对象,包括数据库、表、索引、列、别名、视图、存储过程、分区、表空间和其他对象名称称为标识符。

    如果标识符包含特殊字符或者是保留字,则在引用它时必须引用它。

    依次分配给String 的查询应更改为以下内容以解决此错误!

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

    以下是 MySQL 保留关键字的文档链接 -> Documentation

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2017-08-03
      • 2011-03-28
      • 2015-09-28
      相关资源
      最近更新 更多