Useful Statement Methods: Executequery
Useful Statement Methods: Executequery
• executeQuery
– Executes the SQL query and returns the data in a table
(ResultSet)
1 JDBC
Example Code 15.1
Executing SQL DML Statements
/* This progarm will take two command line argument
that are used to update records in the database */
try {
//steps 2 to 5
Class.forName(“driver name”);
Connection con=null;
con = DriverManager.getConnection(url, usr, pwd);
Statement st = con.createStatement();
2 JDBC
Example Code 15.1
Executing SQL DML Statements (cont.)
//Step 6: Execute the Query / DML
3 JDBC
Example Code 15.1
Executing SQL DML Statements (cont.)
//Step 8: close the connection
con.close();
} //end main
}//end class
4 JDBC
Compile & Execute
Before execution
After execution
5 JDBC
Useful Statement Methods
(Continued)
• getMaxRows( ) / setMaxRows(int)
– Determines the number of rows a ResultSet may
contain
– Unless explicitly set, the number of rows are unlimited
(return value of 0)
• getQueryTimeout( ) / setQueryTimeout(int)
– Specifies the amount of a time (seconds) a driver will
wait for a STATEMENT to complete before throwing a
SQLException
6 JDBC
Different Types of Statements
• Overview
– Through the Statement object, SQL statements are sent
to the database.
– Three types of statement objects are available:
• Statement
– for executing a simple SQL statements
• PreparedStatement
– for executing a precompiled SQL statement passing
in parameters
• CallableStatement
– for executing a database stored procedure
7 JDBC
Prepared Statements
(Precompiled Queries)
• Idea
– If you are going to execute similar SQL statements
multiple times, using “prepared” (parameterized)
statements can be more efficient
– Each time you use it, you simply replace some of the
marked parameters (?) using some set methods
8 JDBC
Prepared Statement, Example
PreparedStatement pStmt =
con.prepareStatement("UPDATE tableName " +
“SET columnName = ? " +
“WHERE columnName = ?");
pStmt.setString(1, stringValue);
pStmt.setInt (2, intValue);
pStmt.executeUpdate();
9 JDBC
Example Code: Modify JdbcDmlEx.java 15.1
Executing Prepared Statements
try {
//steps 2 to 4
Class.forName(“driver name”);
Connection con=null;
con = DriverManager.getConnection(url, usr, pwd);
10 JDBC
Example Code: Modify JdbcDmlEx.java 15.1
Executing Prepared Statements
//Step 5: Create the statement
PreparedStatement pStmt = null;
pStmt.setString(1 , addVar);
pStmt.setString(2, nameVar);
// sql = “UPDATE Person SET address = “defence” WHERE name = “ali” ”
11 JDBC
Example Code: Modify JdbcDmlEx.java 15.1
Executing Prepared Statements
} //end main
}//end class
12 JDBC
Compile & Execute
Before execution
After execution
13 JDBC
ResultSet
Row
numbers ResultSet
0 id Name Address phoneNum
14 JDBC