Using prepaid statements
by , 10-30-2011 at 05:22 PM (834 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:
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.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) …
I will present an example that will show how to use prepaid statements.
Do try this one and try to explore more.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")); }









Email Blog Entry
sorry for all the questions
thanks...
06-14-2013, 02:22 PM in gbonecapone