MySQL封装工具类
将连接数据库的方法进行封装,并在别的类中进行使用,并且要声明静态方法,
//1.获取连接 public static Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/shujuku?&useUnicode=true&serverTimezone=UTC"; String user = "root"; String password = "123456"; connection = DriverManager.getConnection(url,user,password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return connection; }
注意返回值为Connection类型名称为getConnection
将关闭方法进行封装,同样声明成为静态方法
方法名称为closeAll,传入三个参数,为防止空指针异常,需要用if语句判断。
public static void closeall(Connection connection, Statement statement, ResultSet resultSet) { try { if(resultSet != null) resultSet.close(); if(statement != null) statement.close(); if(connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); }
//最终版本 public class JDutil { static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //1.获取连接 public static Connection getConnection() { Connection connection = null; try { String url = "jdbc:mysql://localhost:3306/shujuku"; String user = "root"; String password = "123456"; connection = DriverManager.getConnection(url,user,password); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) { try { if(resultSet != null) resultSet.close(); if(statement != null) statement.close(); if(connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }