Reputation: 53
I'm trying to insert a variable into the database.
Heres my code :
public static void main(String[] args) throws SQLException {
Connection connection =null;
DBhelper helper = new DBhelper();
PreparedStatement statement = null;
ResultSet resultSet;
try{
connection= helper.getConnection();
System.out.println("baglantı olustu");
String sql = "INSERT INTO pandemi(toplamvirus) VALUES ('?') ";
statement = connection.prepareStatement(sql);
statement.setInt(1,2);
statement.executeUpdate(sql);
int result = statement.executeUpdate();
}
catch (SQLException exception){
helper.showErrorMessage(exception);
}
finally {
statement.close();
connection.close();
}
//String sql = "UPDATE pandemi SET toplamvirus='ff' ";
}
And the error is:
baglantı olustu
Error: Parameter index out of range (1 > number of parameters, which is 0).
Error code : 0
The database is: https://prnt.sc/rile7q
Upvotes: 0
Views: 345
Reputation: 340200
setInt
You are incorrectly using the PreparedStatement::setInt
method. The first argument is an ordinal number (incorrectly documented in the Javadoc as an index). So first placeholder is # 1, second placeholder is # 2, and so on. You have only a single ?
placeholder. Or were you trying to pass a value of two to be inserted into the database? Your question is not clear.
?
Also, you need to remove the single-quote marks from around the ?
placeholder in your prepared statement. Using '?'
means you want a single-character string consisting of a question mark inserted into the database. With the single-quotes in place, you have no placeholder in your SQL statement. So your setInt
method will fail. If using a naked ?
, the question mark will be recognized as a placeholder.
By the way, I suggest making a habit of using the SQL statement terminator, a semicolon.
String sql = "INSERT INTO pandemi ( toplamvirus ) VALUES ( ? ) ; ";
For more info, see another Answer of mine with a complete example app using the H2 database engine demonstrating INSERT
with a placeholder in a prepared statement.
Upvotes: 2