Statements in PostgreSQL JDBC
1. To get a statement object, assume you have established
a connection, called con:
E.g.,
Statement stmt = con.createStatement();
2. To use a statement, you can execute a query specified by a string:
E.g.,
String query = "CREATE TABLE myTable
(Name text, Id int, Salary int)";
int i = stmt.execute(query);
if (i == 1) myPrint("table created successfully");
else myPrint("table cannot be created");
Please see Lecture 9 for more details on Statements, and
the various exectute statements, and the use of ResultSets.
3. Each Statement has only one ResultSet. So any execution method
implicitly closes a current open ResultSet.
4. Instead of Statements, you can use PreparedStatement, which
is an extension of Statement. PreparedStatements can take
arguments (indicated by "?"). The arguments are index
by 1, 2, 3, etc (not 0, 1, 2, etc). You can then
use "setXXX" methods to set these arguments to any
values desired (say, inside a loop):
E.g.,
String query = "UPDATE myTable SET Salary = ?
WHERE Id = ?"; // query with 2 arguments
PreparedStatement pstmt = con.preparedStatement(query);
pstmt.setBigDecimal(1, 1234.56); // first argument
pstmt.setInt(2, 111111); // second argument
ResultSet rs = pstmt.executeUpdate();