Using a Prepared Statement


PreparedStatement stmnt =     conn.prepareStatement(         "INSERT into users values (?,?,?,?)"); stmnt.setString(1, name); stmnt.setString(2, password); stmnt.setString(3, email); stmnt.setInt(4, employeeId); stmnt.executeUpdate( );



To create a prepared statement in JDBC, we use a PreparedStatement object in place of a Statement object. We pass the SQL into the prepareStatement() method on the Connection object. This creates a PreparedStatement object. When using a prepared statement, data values in the SQL statement are specified with a question mark. The actual values for these question mark placeholders are set later using the PreparedStatement set methods. The set methods available include setArray(), setAsciiStream(), setBigDecimal(), setBinaryStream(), setBlob(), setBoolean(), setByte(), setBytes(), setCharacterStream(), setClob(), setDate(), setDouble(), setFloat(), setInt(), setLong(), setNull(), setObject(), setRef(), setShort(), setString(), setTime(), setTimestamp(), and setURL(). Each of these set methods is used to set a different type of data as a parameter used in the SQL statement. For example, the setInt() method is used to set integer parameters, the setString() method is used to set String parameters, and so on.

In this phrase, we set three string values and one integer value, using the setString() and setInt() methods. For each question mark that appears in the query statement, there must be a corresponding set statement to set its value. The first parameter to the set statements specifies the position of the parameter being set from the query statement. For example, passing a value of 1 as the first parameter to a set statement will set the value of the first question mark position in the query statement. The second parameter to the set statements specifies the actual value being set. In our phrase, the variables name, password, and email are all assumed to be of type String. The employeeId variable is of type int.

When you are creating a SQL statement that you will reuse multiple times, it is more efficient to use a PreparedStatement instead of a regular Statement object. A prepared statement is a precompiled SQL statement, which makes it faster to execute repeatedly once it has been created.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net