jdbc(二)

参考:https://www.runoob.com/w3cnote/jdbc-use-guide.html

DbUtil

即jdbc工具类,用于提供Connection对象

public class DbUtil {
    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";
    private static Connection conn = null;
    static{
        try {
            //1.加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //2. 获得数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        return conn;
    }
}

Dao类

void add(User user)throws SQLException{
      Connection conn = DbUtils.getConnection();
      //...
}
posted @ 2020-10-12 00:15  黑白猫123  阅读(51)  评论(0编辑  收藏  举报