MySQL Connector/J 发行说明
Statement 对象允许您执行基本的 SQL 查询,并通过 ResultSet 类检索结果,这将在后面描述。
要创建 Statement 实例,您可以在使用前面描述的 DriverManager.getConnection() 或 DataSource.getConnection() 方法检索到的 Connection 对象上调用 createStatement() 方法。
获得 Statement 实例后,您可以通过使用要使用的 SQL 调用 executeQuery(String) 方法来执行 SELECT 查询。
要更新数据库中的数据,请使用 executeUpdate(String SQL) 方法。此方法返回与更新语句匹配的行数,而不是已修改的行数。
如果您事先不知道 SQL 语句是 SELECT 还是 UPDATE/INSERT,则可以使用 execute(String SQL) 方法。如果 SQL 查询是 SELECT,则此方法将返回 true,如果它是 UPDATE、INSERT 或 DELETE 语句,则返回 false。如果该语句是 SELECT 查询,则可以通过调用 getResultSet() 方法来检索结果。如果该语句是 UPDATE、INSERT 或 DELETE 语句,则可以通过在 Statement 实例上调用 getUpdateCount() 来检索受影响的行数。
示例 7.2 Connector/J:使用 java.sql.Statement 执行 SELECT 查询
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
// assume that conn is an already created JDBC connection (see previous examples)
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}