0

我有一个简单的 PreparedStatement 字符串,如下所示:

INSERT INTO albums (name, date) VALUES (?, ?)

我用这个创建了表:

CREATE TABLE "albums" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "name"  TEXT NOT NULL,
    "date"  TEXT NOT NULL
);

这是我能写的最简单的例子:

public static void main(String[] args)
    Connection dbConnection;
    String sqlAlbumQuery = "INSERT INTO albums (name, date) VALUES (?, ?)";
    PreparedStatement statement;

    try {
        dbConnection = DriverManager.getConnection("jdbc:sqlite:plswork.sqlite");
    }
    catch (SQLException e) {
        System.err.println("Failed to establish connection: " + e);
        return;
    }

    try {
        statement = dbConnection.prepareStatement(sqlAlbumQuery);

        statement.setString(0, "some album"); //StatementTest.java:40
        statement.setString(1, "2012"); //StatementTest.java:41

        statement.executeUpdate();
    }
    catch (SQLException e) {
        System.err.println("Failed to create album: " + e);
    }
}

这是我得到的信息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at org.sqlite.core.CorePreparedStatement.batch(CorePreparedStatement.java:130)
    at org.sqlite.jdbc3.JDBC3PreparedStatement.setString(JDBC3PreparedStatement.java:417)
    at statementtest.StatementTest.main(StatementTest.java:40)
C:\Users\notangryatall\AppData\Local\NetBeans\Cache\11.3\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\notangryatall\AppData\Local\NetBeans\Cache\11.3\executor-snippets\run.xml:94: Java returned: 1

我正在使用带有 JDK 1.8 和 sqlite-jdbc-3.30.1 的 Netbeans 11.3。

我尝试更改为 JDK 13,尝试使用较旧的 sqlite-jdbc-3.23.1,尝试在结尾添加分号sqlAlbumQuery,尝试使用statement.executeQuery()代替statement.executeUpdate()并尝试使用 Google,但仍然找不到任何东西。

4

2 回答 2

3

PreparedStatement 文档

第一个参数是1,第二个是2,...

所以你应该打电话给setString(1,...)andsetString(2,...)而不是setString(0,...)andsetString(1,...)

于 2020-06-04T22:08:26.453 回答
2

问题在这里:

statement.setString(0, "some album"); //StatementTest.java:40

Prepare 语句索引从 1 开始(来自 PreparedStatement 接口):

@param parameterIndex the first parameter is 1, the second is 2, ...
于 2020-06-04T22:08:02.390 回答