JDBC——阶段性总结

1、JDBC工作流程

  • 添加jar依赖   
  • Class.forName(“驱动”)
  • Connection con=DriverManager.getConnection(url,username,pwd);
  • PrepareStatement ps=con.PrepareStatement(sql);        Ps.setString(1,””);
  • Insert update  delete--- int ret=ps.executeUpdate();        Select             ---ResultSet rs=ps.executeQuery();
  • 遍历结果集ResultSet
  • 关闭资源,后创建的先关闭

2、封装了工具类

public class DruidUtils {
    private static DruidDataSource dataSource=null;

    private static ThreadLocal threadLocal;

    static{
        //1 创建流
        try {

            threadLocal=new ThreadLocal<>();

            InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("database.properties");
            Properties properties=new Properties();
            properties.load(is);

            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池失败....");
            //日志
        }

    }
     

    //获取数据源
    public static DataSource getDataSource(){
        return dataSource;
    }


    //获取连接
    public static Connection getConnection() throws SQLException {
        Connection conn=threadLocal.get(); //Thread.curentThread;
        if(conn==null){
            conn=dataSource.getConnection();
            //放入threadLocal
            threadLocal.set(conn);

        }
        return  conn;
    }


    //开启事务
    public static void beginTransaction() throws  SQLException{
        Connection conn = getConnection();
        conn.setAutoCommit(false);

    }

    //提交事务
    public static void commit() throws SQLException{
        Connection conn = getConnection();
        conn.commit();
    }

    //回滚事务
    public static void roolback() throws SQLException{
        Connection conn = getConnection();
        conn.rollback();
    }

    //关闭
    public static void close() throws SQLException{
        Connection conn = getConnection();
        conn.close();
        threadLocal.remove();

    }

}

        3、数据源、连接池

           Druid c3p0

分层开发 利用MVC模式:dao   service  controllers

你可能感兴趣的:(mysql,java,mysql)