import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBManager { public static final String DRIVER = "com.mysql.jdbc.Driver"; public static final String URL = "jdbc:mysql://localhost:3306/Library_System?useUnicode=true&characterEncoding=UTF-8"; public static final String USER = "root"; public static final String PASSWORD = "java"; /** * 得到连接 * @param url * @param user * @param password * @return * @throws Exception */ public static Connection getConn() throws Exception{ Class.forName(DRIVER); return DriverManager.getConnection(URL, USER,PASSWORD); } /** * 关闭连接 * @param con * @param pStatement * @param rSet */ public static void close(Connection con,PreparedStatement pStatement,ResultSet rSet){ if(null != con){try {con.close();} catch (SQLException e) {}finally{con = null;}} if(null != pStatement){try {pStatement.close();} catch (SQLException e) {}finally{pStatement = null;}} if(null != rSet){try {rSet.close();} catch (SQLException e) {}finally{rSet = null;}} } /** * 封装insert(),update(),delete()方法对数据库的操作 * @param sql * @param params * @return result 返回影响的行数 * @throws Exception */ public static int MySqlExecuteUpdate(String sql,Object...params)throws Exception{ Connection conn = TransAnctionFilter.Transcon.get();//从本地线程里取出conn //Connection conn = getConn(); PreparedStatement pStatement = conn.prepareStatement(sql); for(int i = 0;i < params.length;i++){ pStatement.setObject(i + 1, params[i]); } int result = pStatement.executeUpdate(); close(null, pStatement, null); return result; } /** * 封装select()方法对数据库的操作 * @param sql * @param params * @return 返回查询的结果集 * @throws Exception */ public static ResultSet MySqlExecuteSelect(String sql,Object...params)throws Exception{ Connection conn = TransAnctionFilter.Transcon.get();//从本地线程里取出conn //Connection conn = getConn(); PreparedStatement pStatement = conn.prepareStatement(sql); for(int i = 0;i < params.length;i++){ pStatement.setObject(i + 1, params[i]); } ResultSet rSet = pStatement.executeQuery(); return rSet; } }
最近下载更多