PreparedStatement Example in Java

Here is a quick and dirty example on writing a prepared statement in Java.

There are a few things you could change in this design.

1. Seperate the code for the SQL command and PreparedStatement

2. Make something like a for loop around pState.setObject()

 


// This will create a simple one query for a single column in a database
// Also this should be inside a try catch and there are a few variables not init in this script.
//-------------------------------------------------
// DBconnection - This is the database connection.
// tableName - String of the name of the table we are going to query.
// column - String of the database column where going to search.
// obj - The object where going to search in the database column.
//-------------------------------------------------

ResultSet rset = null; // The prepared statement will be executed

// This code block will create the string for the SQL request
String statement= "SELECT * FROM "
statement += tableName; // In this case tableName is a string variable of the table we are going to query
statement += " WHERE ";
statement += column; // In this case column is a string variable of the database column
statement += " = ?";   // This is where the value will inserted

// This code block will create our prepared statement
PreparedStatement pState = DBconnection.preparedStatement; // This is the driver connection to the database.  I'm not covering how to make a connection in this example
pState.setObject(1, obj); // 1 is a reference to which "?" mark the object will be inserted into.  obj is the variable where going to query in the database

// This line will execute the query and packages the data into a ResultSet
rset = ps.executeQuery();
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s