Writing SQL Prepared Statements in Java

There are two things you need to do to write a prepared statement in Java.  First your going to need an SQL string  with ?s in place of the values.   Second we add the values to the statement by calling the set methods of the preparedstatement.  PreparedStatement.setString(1, AnyStringData) will set the first question mark in the SQL string with “AnyStringData”.

//Untested Pseudo Code && Ugly method

public void makePreparedStatement(Connection connect)

//SQL String

String sql = "UPDATE MEMBERS SET NAME = ? WHERE ID = ?";

PreparedStatement ps = connect.prepareStatement(sql);

ps.setString(1, Dan); //Value for the ? at the Name field

ps.setInt(2, 1); // Value for the ? at the ID field

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s