java管理系统类源代码 javaweb简单管理系统源码( 二 )


? executeUpdate方法也可以执行类似于CREATE TABLE和DROP TABLE语句的SQL数据定义语言(DDL)语句
? executeUpdate方法的返回值是一个整数,指示受影响的行数(即更新计数) 。而对于CREATE TABLE 或 DROP TABLE等并不操作特定行的语句,executeUpdate的返回值总为零 。
execute方法
execute方法用于执行:
? 返回多个结果集
? 多个更新计数
? 或二者组合的语句
execute方法
? 返回多个结果集:首先要调用getResultSet方法获得第一个结果集 , 然后调用适当的getter方法获取其中的值 。要获得第二个结果集,需要先调用getMoreResults方法 , 然后再调用getResultSet方法 。
? 返回多个更新计数:首先要调用getUpdateCount方法获得第一更新计数 。然后调用getMoreResults,并再次调用getUpdateCount获得后面的更新计数 。
? 不知道返回内容:如果结果是ResultSet对象,则execute方法返回true;如果结果是int类型,则意味着结果是更新计数或执行的语句是DDL命令 。
execute方法
为了说明如果处理execute方法返回的结果,下面举一个代码例子:
stmt.execute(query);
while (true){
int row = stmt.getUpdateCount();
//如果是更新计数
if (row0) {
System.out.println("更新的行数是:" + row);
stmt.getMoreResults();
continue;
}
execute方法
//如果是DDL命令或0个更新
if (row == 0) {
System.out.println("没有更新,或SQL语句是一条DDL语句!");
stmt.getMoreResults();
continue;
}
//如果是一个结果集
ResultSet rs = stmt.getResultSet;
if (rs != null) {
while (rs.next()){
// 处理结果集
. . .
}
stmt.getMoreResults();
continue;
}
break;
}
PreparedStatement 语句
登录一个网站或BBS时 :
? 使用Statement语句
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery
(“SELECT password FROM userinfo
WHERE id=userId");
? 使用PreparedStatement语句
PreparedStatement pstmt=conn.prepareStatement
(“SELECT password FROM userinfo
WHERE id=?");
pstmt.setString(1, userId);
PreparedStatement语句
? 常用的setter方法
public void setBoolean(int parameterIndex, boolean x) throws SQLException;
public void setByte(int parameterIndex, byte x) throws SQLException;
public void setShort(int parameterIndex, short x) throws SQLException;
public void setInt(int parameterIndex,int x) throws SQLException;
public void setLong(int parameterIndex, long x) throws SQLException;
public void setFloat(int parameterIndex, float x) throws SQLException;
public void setDouble(int parameterIndex, double x) throws SQLException;
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException;
public void setString(int parameterIndex, String x) throws SQLException;
public void setBytes(int parameterIndex, byte[] x) throws SQLException;
public void setDate(int parameterIndex, Date x) throws SQLException;
public void setTime(int parameterIndex, Time x) hrows SQLException;
public void setTimestamp(int parameterIndex, Timestamp x)throws SQLException;
PreparedStatement语句
? PreparedStatement接口是由Statement接口扩展而来的,重写了executeQuery方法、executeUpdate方法和execute 方法
? public ResultSet executeQuery() throws SQLException
? public int executeUpdate() throws SQLException
? public boolean execute() throws SQLException
CallableStatement语句
? CallableStatement语句是由Connection接口的prepareCall方法创建的,创建时需要传入字符串参数 , 参数的形式为:
? {call procedure_name[(?, ?, ...)]}

推荐阅读