View RSS Feed

My Java Tips

Using prepaid statements

Rate this Entry
by , 10-30-2011 at 06:22 PM (1455 Views)
SQL statements are executed on a database tables using Statement object. If the sql statement takes parameter, then it is a wise decision to use PreparedStatement as they are more flexible and makes coding easier.


Creating SQL statements that take parameters provides flexible statements to work with. We can use the same statement and supply it with different values each time we execute it.
We use place holders (question marks) in the query, which are supplied values to make queries flexible. Values are supplied using setXx() methods for example:

Java Code:
void setDouble(int parameterIndex, double x)
void setFloat(int parameterIndex, float x)
void setInt(int parameterIndex, int x)
void setLong(int parameterIndex, long x) 
One has to specify the index as well while setting values. If we miss a parameter or supply an extra parameter, then org.postgresql.util.PSQLException is thrown. Time for an example. I will connect to Postgres database and will display the contents of a table. Then I will use PreparedStatement statement to update a record and for confirmation, I will again display the contents of the table.

I will present an example that will show how to use prepaid statements.


Java Code:
PreparedStatement ps = conn.prepareStatement("select * from programming where name LIKE ?");
ps.setString(1, "Java");

		ResultSet rs = ps.executeQuery();
		while(rs.next())
		{
			System.out.print(rs.getString("name"));
			System.out.println(" - " + rs.getString("comments"));
		}
Do try this one and try to explore more.

Submit "Using prepaid statements" to Facebook Submit "Using prepaid statements" to Digg Submit "Using prepaid statements" to del.icio.us Submit "Using prepaid statements" to StumbleUpon Submit "Using prepaid statements" to Google

Tags: None Add / Edit Tags
Categories
JDBC

Comments