JDBC(封装 批处理 存储过程 函数 自增长)

封装JDBC连接数据库

public class JDBCUtils {

    private static String url;
    private static String username;
    private static String password;

    private JDBCUtils() {
    }

    static {
        try {
            //这些连接数据库的基本参数,写在代码里写死了,不好。
            //要配合配置文件,把这些参数写到配置文件里,代码里面读取配置文件中的内容

            //读取配置文件
            Properties properties = new Properties();
            properties.load(new FileReader("mysqlLogin.properties"));

            username = properties.getProperty("username");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            String driverClassName = properties.getProperty("driverClassName");

            Class.forName(driverClassName);

        } catch (ClassNotFoundException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接对象
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //释放资源
    public static void close(Connection conn, Statement statement, ResultSet resultSet) throws SQLException {
        if (conn != null) {
            conn.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (resultSet != null) {
            resultSet.close();
        }
    }

    //释放资源
    public static void close(Connection conn, Statement statement) throws SQLException {
        if (conn != null) {
            conn.close();
        }
        if (statement != null) {
            statement.close();
        }
    }
}

批处理

概念讲述

在调用prepareStatement.executebatch();代码时,
	开启rewriteBatchedStatements会成倍提高执行效率
不开启则是单条sql提交
开启则是多条sql提交
但提交的sql不能超过max_allowed_packet的设置值 不然会报错

查询max_allowed_packet方法
进入mysql容器 运行
mysql> show variables like 'max_allowed_packet';
+--------------------+---------+
| Variable_name      | Value   |
+--------------------+---------+
| max_allowed_packet | 4194304 |
+--------------------+---------+
max_allowed_packet的单位为字节。

插入大量数据时 建议使用批处理来做
statement.addBatch();//添加批处理,先将数据缓存起来
statement.executeBatch();//执行批处理
statement.clearBatch();//清空缓存

代码实现

public class JDBCMore {
    public static void main(String[] args) throws Exception {
        //批处理,在url上要开启一下:rewriteBatchedStatements=true
        //jdbc:mysql://localhost:3306/mydb
        // ?serverTimezone=Asia/Shanghai
        // &useUnicode=true
        // &characterEncoding=UTF-8
        // &useSSL=false
        // &rewriteBatchedStatements=true
        
        //测试数据
        ArrayList<User> list = new ArrayList<>();
        for (int i = 0; i < 20000; i++) {
            User user = new User("测试数据" + i, "123456");
            list.add(user);
        }
        
        //获取连接对象
        Connection conn = JDBCUtils.getConnection();
        
        String sql = "insert into user(username, password) values(?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);

        for (User user : list) {
            //给sql语句中的问号?赋值
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            //preparedStatement.executeUpdate(); //这样是一条一条插入的,效率慢
            //可以批量插入
            preparedStatement.addBatch(); //添加批处理
        }
        
        //执行批处理
        preparedStatement.executeBatch();
        //清空批处理
        preparedStatement.clearBatch();
        //释放资源
        JDBCUtils.close(conn, preparedStatement);
    }
}

JDBC调用存储过程和函数

调用存储过程

调用存储过程 {call <procedure-name>[(<arg1>,<arg2>, ...)]}

public class JDBCPro {
    public static void main(String[] args) throws Exception {
        /*
        CallableStatement用于执行SQL存储过程的接口
        JDBC API提供了一个存储过程SQL转义语法,该语法允许对所有RDBMS使用标准方式调用存储过程。
        此转义语法有一个包含结果参数的形式和一个不包含结果参数的形式。
        如果使用结果参数,则必须将其注册为OUT参数。
        其他参数可用于输入、输出或同时用于二者。参数是根据编号按顺序引用的,第一个参数的编号是 1。

        {call<procedure -name >[( < arg1 >,<arg2 >, ...)]}

        IN参数值是使用继承自PreparedStatement的set方法设置的.
        在执行存储过程之前,必须注册所有OUT参数的类型;
        它们的值是在执行后通过此类提供的get方法获取的。
        */

        Connection conn = JDBCUtils.getConnection();

        CallableStatement callableStatement
                = conn.prepareCall("{call myPro(?,?)}");
        callableStatement.setString(1,"hehe");
        //如果有输出参数我们需要注册输出参数
        callableStatement.registerOutParameter(2, Types.INTEGER);
        //执行
        callableStatement.execute();
        //获取输出结果
        int anInt = callableStatement.getInt(2);
        System.out.println(anInt);

        JDBCUtils.close(conn,callableStatement);
    }
}

调用函数

调用自定义函数 {?=call<procedure -name >[( < arg1 >,<arg2 >, ...)]}

public class JDBCFun {
    public static void main(String[] args) throws Exception {
        // {?=call<procedure -name >[( < arg1 >,<arg2 >, ...)]}
        // 第一个问号是返回的值 第二个问号是传入的值

        Connection conn = JDBCUtils.getConnection();
        CallableStatement callableStatement
                = conn.prepareCall("{?=call md5(?)}");
        //设置输入参数
        callableStatement.setString(2, "123456");
        //注册返回值
        callableStatement.registerOutParameter(1, Types.VARCHAR);
        //执行
        callableStatement.execute();
        //获取返回的结果
        String str = callableStatement.getString(1);
        System.out.println("结果是: " + str);
        //释放资源
        JDBCUtils.close(conn,callableStatement);
    }
}

获取自增长键的值

概念讲述

1.要获取自增长键的值 需要在获取操作对象时声明一个参数 Statement.RETURN_GENERATED_KEYS
	PreparedStatement preparedStatement 
		= conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
 
2.当数据插入成功后 就可以取出这个自增长键的值
	//获取自增长键的结果集
    ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
    while (generatedKeys.next()){
        keyValue = generatedKeys.getInt(1);
	}
            
3.你在其他表中就可以使用这个自增长键的值           
    INSERT INTO mylog(id, content, mydate) VALUES (NULL,'hehehe',NULL)
    SELECT LAST_INSERT_ID(); -- 这个函数也可以获取最后新增这条数据的自增长键的值

代码实现

public class JDBCKeys {
    public static void main(String[] args) throws SQLException {
        //获取自增长的键的值
        Connection conn = JDBCUtils.getConnection();
        //要获取自增长键的值
        //需要在获取操作对象时声明一个参数
        //Statement.RETURN_GENERATED_KEYS
        String sql = "insert into user(username,password) values (?,?)";
        PreparedStatement preparedStatement 
                = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1,"abc");
        preparedStatement.setString(2,"123456");

        int i = preparedStatement.executeUpdate();
        ResultSet generatedKeys = null;
        if (i > 0) {
            System.out.println("插入成功");
            //获取自增长键的集合
            generatedKeys = preparedStatement.getGeneratedKeys();
            int id = 0;
            while (generatedKeys.next()) {
                id = generatedKeys.getInt(1);
            }
            System.out.println(id);
        } else {
            System.out.println("插入失败");
        }
        JDBCUtils.close(conn, preparedStatement, generatedKeys);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值