Using Prepared Statement
The PreparedStatement object represents a precompiled SQL statement. A PreparedStatement can be used multiple times, and helps avoid SQL injection attacks. A PreparedStatement can be a SELECT, INSERT, UPDATE or DELETE statement.
To use a prepared statement establish a connection as described in Querying the Data. then create a PreparedStatement, set the parameter(s), and execute it.
The example below shows a SELECT PreparedStatement, please note that the parameter indices start from one.
String query = "SELECT * FROM Account WHERE Id=? and Name=?"; //It's equivalent to "SELECT * FROM Account WHERE Id='XXX' and Name='YYY'"
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, "XXX");
pstmt.setString(2, "YYY");
boolean ret = pstmt.execute();
if (ret){
ResultSet rs=pstmt.getResultSet();
while(rs.next()){
for(int i=1;i<=rs.getMetaData().getColumnCount();i++)
{
System.out.println(rs.getMetaData().getColumnName(i) +"="+rs.getString(i));
}
}
}