Suppose you have two variables nameVal and catVal from which you want to create a new record in the animal table. To do so without regard to whether or not the values contain special characters, issue the query like this:
PreparedStatement s;
s = conn.prepareStatement (
"INSERT INTO animal (name, category) VALUES(?,?)");
s.setString (1, nameVal);
s.setString (2, catVal);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");The '?' characters in the query string act as placeholders--special markers indicating where data values should be placed. The setString() method takes a placeholder position and a string value and binds the value to the appropriate placeholder, performing any special-character escaping that may be necessary. The method you use to bind a value depends on the data type. For example, setString() binds string values and setInt() binds integer values.
No comments:
Post a Comment