JDBC及代码分层

JDBC是基于JAVA语言访问数据库的一种技术

JDBC中连接mysql的jar包分享:

链接:https://pan.baidu.com/s/1pncAno7AMDfSpPrNJN4TRg
提取码:hjw6

SPI作用:通过这个约定,就不需要把服务放在代码中了,通过模块被装配的时候就可以发现服务类了Springboot中SPI机制及自动装配 - Jessica888 - 博客园

package com;

import java.sql.*;

public class JDBCTest {
    public static void main(String[] args) throws Exception {
        //Class.forName("mysql.jdbc.jdf.Driver");
        //加载驱动
        String URL = "jdbc:mysql://localhost:3306/ceshi?serverTimezone=GMT%2B8";
        String username = "root";
        String password = "root";
        Connection conn = DriverManager.getConnection(URL,username,password);
        //测试连接是否成功
        //System.out.println(conn);
        //定义sql语句
        String sql = "select * from jiancha";
        //准备静态处理块对象,将sql语句放入静态处理块中,理解为存放sql语句的地方
        Statement statement = conn.createStatement();
        //执行数据库语句,返回结果集
        ResultSet resultSet = statement.executeQuery(sql);
        /* 
        * statement在执行的时候可以选择三种方式:
        * 1.execute:任何sql语句都可以执行
        * 2.executeQuery:只能执行查询语句
        * 3.executeUpdate:只能执行语句
        */
        while(resultSet.next()){
            String username1 = resultSet.getString("user");
            System.out.print(username1+"    ");
            String password1 = resultSet.getString("password");
            System.out.println(password1);
        }
        //循环迭代
        //循环迭代,使用while循环有两种获取方式,第一种方式通过下标索引编号来获取,从1开始
        // 第二种是通过列名来获取,推荐使用列名,列名一般不会发生修改
        conn.close();
        //关闭数据库
    }
}

批量提交:

package com;

import com.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BatchDaolmpl {
    public static void main(String[] args) {
        insertBatch();
    }

    public static void insertBatch(){
        Connection connection = DBUtil.getConnection();
        PreparedStatement pstmt = null;
        String sql = "insert into psm (id,name) values(?,?)";
        //准备预处理块
        try {
            pstmt = connection.prepareStatement(sql);
            for(int i=0;i<10;i++){
                pstmt.setInt(1,i+1000);
                pstmt.setString(2,"hjw"+i);
                //向批处理中添加sql语句
                pstmt.addBatch();
            }
            int[] ints = pstmt.executeBatch();
            for (int anInt:ints){
                System.out.println(anInt);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeConnection(connection,pstmt);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值