Reputation: 23
I have a simple PreparedStatement string like this:
INSERT INTO albums (name, date) VALUES (?, ?)
I have created the table with this:
CREATE TABLE "albums" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" TEXT NOT NULL,
"date" TEXT NOT NULL
);
This is the simplest example I could write:
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);
}
}
and this is the message I get:
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
I am using Netbeans 11.3 with JDK 1.8 and sqlite-jdbc-3.30.1.
I tried changing to JDK 13, tried using older sqlite-jdbc-3.23.1, tried adding semicolon to end of the sqlAlbumQuery
, tried using statement.executeQuery()
instead of statement.executeUpdate()
and tried Google but still couldn't find anything.
Upvotes: 2
Views: 873
Reputation: 59186
From the PreparedStatement docs:
the first parameter is 1, the second is 2, ...
So you should be calling setString(1,...)
and setString(2,...)
instead of setString(0,...)
and setString(1,...)
Upvotes: 4
Reputation: 61
Issue is here:
statement.setString(0, "some album"); //StatementTest.java:40
Prepare statement index starts from 1(from PreparedStatement interface):
@param parameterIndex the first parameter is 1, the second is 2, ...
Upvotes: 3