【问题标题】:SQL increment id, filling first line of databaseSQL增量id,填充数据库第一行
【发布时间】:2017-09-24 02:31:39
【问题描述】:

我在 java (eclipse) 中使用库 sqlite-jdbc-3.16.1.jar 建立了一个 sqlite 数据库。

table1 中有 5 行:id(ID Integer PRIMARY KEY AUTOINCREMENT), name, row3, row4, row5

我想插入名称、row3 和 row4 以及 id 以增加自身。

public static void insertTest(String name, byte[] contentRow3, byte[] contentRow4) {

          String sql = "INSERT INTO table1(name, contentRow3, contentRow4) VALUES(?,?,?)";

            try (Connection conn = connect();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(2, name);
                pstmt.setBytes(3, contentRow3);
                pstmt.setBytes(4, contentRow4);
                System.out.println("Added new Person to DB");
                pstmt.executeUpdate();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }

错误:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

这里有什么问题?

【问题讨论】:

    标签: eclipse sqlite indexoutofboundsexception


    【解决方案1】:

    Javaprepared statements 中的占位符从索引 1 开始,而不是 2。我希望以下更正的代码应该可以工作:

    try (Connection conn = connect();
        PreparedStatement pstmt = conn.prepareStatement(sql)) {
        pstmt.setString(1, name);
        pstmt.setBytes(2, contentRow3);
        pstmt.setBytes(3, contentRow4);
        System.out.println("Added new Person to DB");
        pstmt.executeUpdate();
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    

    您遇到的异常是抱怨索引位置 3 超出范围。最有可能的是,当您执行 pstmt.setBytes(3, contentRow4) 时,这会转化为访问 第四 数组元素,假设数组索引从零开始,该元素将是索引 3。

    【讨论】:

    • 所以setString后面的数字不是行号?
    • 您在PreparedStatement 上设置的值对应于 SQL 查询中的问号占位符。索引从 1 开始,由于您有 3 个问号,因此您应该设置 1、2 和 3。
    猜你喜欢
    • 2012-07-04
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2016-01-17
    • 2012-03-08
    • 1970-01-01
    相关资源
    最近更新 更多