MYSQL---JDBC高级 封装JDBC实现增删改

  1. 在database.properties中配置 驱动信息,3个连接信息—url、username、password

com.mysql.jdbc.Driver 是 mysql-connector-java 5中的,
com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6中的

①com.mysql.jdbc.Driver 的写法:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=007

②Mysql6 com.mysql.cj.jdbc.Driver,的写法:
需要指定时区serverTimezone

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=

创建JDBCUtils (获取数据库连接、关流):

/**可调用的静态方法:
 *          获取数据库连接 -----Connection
 *          关3流 ----ResultSet、Statement、Connection
 */
public class JDBCUtils {

    private static DataSource ds;
    private static Connection con;

    //获取 数据源ds
    static{
        try {
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接
     * @return
     */
    public static Connection getCon(){
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            return null;
        }
    }


    /**
     * 关流
     *      结果集ResultSet   预处理对象父类Statement  连接connection
     */
    public static void close(ResultSet rs, Statement st,Connection con){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if(con!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

3.创建JDBCOperation —update方法 增删改

public class JDBCOperation {

    /**
     * 增删改  ---executeUpdate
     * @param sql  带?的sql语句
     * @param obj  sql中加入?的数组
     * @return 成功更新的 数量
     */
    public int doUpdate(String sql,Object[] obj){
        Connection con=null;
        PreparedStatement st=null;
        try {
            con=JDBCUtils.getCon();
            st=con.prepareStatement(sql);

            if(obj!=null){
                for (int i = 0; i <obj.length ; i++) {
                    st.setObject(i+1,obj[i]);
                }
            }

            int num = st.executeUpdate(sql);
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(null,st,con);
        }
        return -1;
    }
}

发布了11 篇原创文章 · 获赞 7 · 访问量 222

猜你喜欢

转载自blog.csdn.net/weixin_45881192/article/details/104075397
今日推荐