因为数据库的连接代码都是固定的,为了将减少重复的代码的书写,可以将这些代码封装为一个工具类,获取数据库的连接对象。
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 7 public final class JDBCUtils {// 不能被继承或重写 8 private JDBCUtils() { 9 } 10 11 private static Connection con; 12 13 static { 14 try { 15 Class.forName("com.mysql.jdbc.Driver"); 16 String url = "jdbc:mysql://localhost:3306/student mangement system"; 17 String username = "root"; 18 String password = "root"; 19 con = DriverManager.getConnection(url, username, password); 20 } catch (Exception e) { 21 e.printStackTrace(); 22 throw new RuntimeException(e + "数据库连接失败"); 23 } 24 } 25 26 public static Connection getConnection() { 27 return con; 28 } 29 30 public static void close(Connection con, Statement stat) { 31 32 if (stat != null) { 33 try { 34 stat.close(); 35 } catch (SQLException e) { 36 e.printStackTrace(); 37 System.out.println("stat流关闭异常!"); 38 } 39 } 40 41 if (con != null) { 42 try { 43 con.close(); 44 } catch (SQLException e) { 45 e.printStackTrace(); 46 System.out.println("con流关闭异常!"); 47 } 48 } 49 50 } 51 52 public static void close(Connection con, Statement stat, ResultSet rs) { 53 if (rs != null) { 54 try { 55 rs.close(); 56 } catch (SQLException e) { 57 e.printStackTrace(); 58 System.out.println("rs流关闭异常!"); 59 } 60 } 61 62 if (stat != null) { 63 try { 64 stat.close(); 65 } catch (SQLException e) { 66 e.printStackTrace(); 67 System.out.println("stat流关闭异常!"); 68 } 69 } 70 71 if (con != null) { 72 try { 73 con.close(); 74 } catch (SQLException e) { 75 e.printStackTrace(); 76 System.out.println("con流关闭异常!"); 77 } 78 } 79 80 } 81 }
测试工具类:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Test { public static void main(String[] args)throws Exception { Connection con = JDBCUtils.getConnection(); PreparedStatement pst = con.prepareStatement("SELECT sname,studentno FROM student"); ResultSet rs = pst.executeQuery(); while(rs.next()){ System.out.println(rs.getString("sname")+" "+rs.getString("studentno")); } JDBCUtils.close(con, pst, rs); } }