Java PreparedStatement .setString (int parameterIndex, String x)
Syntax
PreparedStatement.setString(int parameterIndex, String x) has the following syntax.
void setString(int parameterIndex, String x) throws SQLException
Example
In the following code shows how to use PreparedStatement.setString(int parameterIndex, String x) method.
/*from www .ja v a2 s. c om*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws Exception {
try {
String url = "jdbc:odbc:databaseName";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "guest";
String password = "guest";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url,user, password);
String changeLastName = "UPDATE authors SET lastname = ? WHERE authid = ?";
PreparedStatement updateLastName = connection.prepareStatement(changeLastName);
updateLastName.setString(1, "Martin"); // Set lastname placeholder value
updateLastName.setInt(2, 4); // Set author ID placeholder value
int rowsUpdated = updateLastName.executeUpdate(); // execute the update
System.out.println("Rows affected: " + rowsUpdated);
connection.close();
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}