java对数据库操作简单处理,如下代码即可,封装了 增删改查及获取连接、关闭连接。
代码如下:
package com.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * 操作数据库工具类 * * */ public class DbUtil { /** * 连接数据 * * @return conn */ public static Connection getConnection(String driver,String url,String username,String password) { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 关闭连接对象 * * @param conn * 连接对象 * @param pstmt * 预编译对象 * @param rs * 结果集 */ public static void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } /** * 增删改操作 * * @param sql * SQL命令 * @param param * 参数 * @return */ public static int executUpdate(Connection conn,String sql, Object[] param) { int result = 0; PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(sql); if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setObject(i + 1, param[i]); } } result = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { closeAll(conn, pstmt, null); } return result; } /** * 查询 * * @return int * @date 2015-7-25 上午11:10:06 */ public static ResultSet executQuery(Connection conn,String sql, String[] param) { PreparedStatement pstmt = null; ResultSet result = null; try { pstmt = conn.prepareStatement(sql); if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setString(i + 1, param[i]); } } result = pstmt.executeQuery(); } catch (Exception e) { e.printStackTrace(); } return result; } }
时间: 2024-10-15 14:43:39