使用JDBC连接数据库 (5)

if (params != null && params.length > 0) {

// 循环给sql语句的参数赋值

for (int i = 0; i < params.length; i++) {

pstmt.setObject(i + 1, params[i]);

}

}

}

 

/**

 * 执行增、删、改sql语句的通用方法

 *

 * @param sql    要执行的sql语句

 * @param params sql语句需要的参数,为null时表示sql语句没有参数

 * @return 受影响的行数

 * @throws Exception

 */

public static int update(String sql, Object[] params) {

int row = 0;// 保存执行后受影响的行数

Connection conn = null;// 连接对象

PreparedStatement pstmt = null;// 命令对象,预编译

try {

// 1、获取连接对象(调用ConnectionUtil类中的getConn()方法)

conn = getConn();

// 2、获取命令对象

pstmt = conn.prepareStatement(sql);

// 判断sql语句是否需要设置参数

if (params != null) {

setParams(pstmt, params);

}

// 3、执行sql语句

row = pstmt.executeUpdate();

} catch (Exception ex) {

ex.printStackTrace();

 

} finally {

// 关闭资源

closeAll(conn, pstmt, null);

}

return row;

}

 

/**

 * 查询的通用方法

 *

 * @param sql    要执行的sql语句

 * @param params sql语句需要的参数数组

 * @return result对象

 */

public static Result getResult(String sql, Object[] params) {

 

Connection conn = null;// 连接对象

PreparedStatement pstmt = null;// 命令对象

ResultSet rs = null;// 结果集

Result result = null;

try {

// 获取连接对象

conn = getConn();

// 根据连接对象获取命令对象

pstmt = conn.prepareStatement(sql);

// 判断sql语句是否需要设置参数

if (params != null) {

setParams(pstmt, params);

}

// 执行命令

rs = pstmt.executeQuery();

// 把结果集转换为result对象

result = ResultSupport.toResult(rs);

 

} catch (Exception ex) {

ex.printStackTrace();

} finally {

// 关闭资源

closeAll(conn, pstmt, rs);

}

 

return result;

}

/**

 * -查询的通用方法 - 这个方法容易报错

 *

 * @param sql    要执行的sql语句

 * @param params sql语句需要的参数数组

 * @return result对象

 */

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzdxfz.html