Java-jdbc-封装类形式的数据库操作
1、建立数据库连接的类
package cn.bruce.MySql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Conutils { //创建数据库连接的工具类 private static Connection con=null; static { String usename = "root"; String password = "jinqi1986"; String url = "jdbc:mysql://localhost:3306/mytrain?useSSL=false&serverTimezone=CTT"; String jdbc = "com.mysql.cj.jdbc.Driver"; try { Class.forName(jdbc); con = DriverManager.getConnection(url, usename, password); } catch (Exception e) { throw new RuntimeException(e + "数据库连接失败!"); } } public static Connection recon() { return con; } //创建数据库关闭的工具类(查询) public static void close(Connection con,Statement st,ResultSet rs){ if (rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st!=null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con!=null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } //创建数据库关闭的工具类(非查询) public static void close(Connection con,Statement st){ if (st!=null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con!=null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2、建立存放集合的封装类
package cn.bruce.MySql; public class sort { private int zid; private String zname; private double zprice; private String zdesc; // 有参构造器 public sort(int zid, String zname, double zprice, String zdesc) {// 依照数据库里的表字段类型创建 this.zid = zid; this.zname = zname; this.zprice = zprice; this.zdesc = zdesc; } // 无参构造器 public sort() { } // get/set方法 public int getZid() { return zid; } public void setZid(int zid) { this.zid = zid; } public String getZname() { return zname; } public void setZname(String zname) { this.zname = zname; } public double getZprice() { return zprice; } public void setZprice(double zprice) { this.zprice = zprice; } public String getZdesc() { return zdesc; } public void setZdesc(String zdesc) { this.zdesc = zdesc; } // 重写toString public String toString() { return "sort [zid=" + zid + ", zname=" + zname + ", zprice=" + zprice + ", zdesc=" + zdesc + "]"; } }
3、建立main类
package cn.bruce.MySql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class useutli { public static void main(String[] args) throws Exception { // 调用数据库连接的工具类 Connection connection = Conutils.recon(); String sql = "select * from test;"; PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery(); // 建立泛型-sort类型list集合 List<sort> list = new ArrayList<sort>(); while (rs.next()) { sort s = new sort(rs.getInt("zid"), rs.getString("zname"), rs.getDouble("zprice"), rs.getString("zdesc")); list.add(s); } Conutils.close(connection, ps, rs); // 遍历 list for (sort s : list) { System.out.println(s); } } }