JDBC详细使用

JDBC

​ JDBC是一种标准,一种规则,主要作用是使用java语言操作数据库的
​ JDBC这个标准中有很多的接口,接口中有很多方法

JDBC开发步骤以及详解

1.准备

1.导入jar包
mysql-connector-java-8.0.25.jar
2.四大核心对象
DriverManager类: 注册驱动 -> 我们需要知道我们操作的是哪款数据库
Connection接口:连接数据库用的
Statement接口:执行sql语句用的
ResultSet接口:结果集接口 -> 主要用于处理查询操作的

2.详细步骤

1.注册驱动:DriverManager类

2.获取连接:DriverManager类中的静态方法 -> 返回的是Connection

static Connection getConnection(String url, String user, String password)

url:数据库的地址
user:数据库用户名
password:数据库用户密码

3.准备sql语句:写sql

4.获取执行平台:Connection中的方法 -> 返回的是Statement对象 -> 主要用于执行sql语句

Statement createStatement();

5.执行sql:Statement中的方法

int executeUpdate(String sql) //针对于增删改  ResultSet executeQuery(String sql) //针对于查询

6.处理结果集:ResultSet接口中的方法:

boolean next()  //判断有没有下一个元素  
getxxx()        //获取元素   

7.关闭资源:
close方法
结果集关闭 ResultSet
执行平台关闭 Statement
连接关闭 Connection

3.具体例子

使用数据表

以下四个代码分别是增删改查的例子

public void insert() throws Exception {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接,连接数据库
        String url = "jdbc:mysql://localhost:3306/day01";
        String name = "root";
        String password = "zsy20040820";
        Connection connection = DriverManager.getConnection(url, name, password);
        //3.准备sql语句
        String sql = "INSERT INTO `user`(username,password)VALUES('tom',123)";
        //4.获取执行平台Connection中的方法:
        //            Statement createStatement()
        Statement st = connection.createStatement();
        //5.执行sql:Statement中的方法
        //int executeUpdate(String sql) -> 针对于增删改操作的
        int i = st.executeUpdate(sql);
        System.out.println("i = " + i);
        //6.由于增删改不需要处理结果集,所以直接关闭资源
        st.close();
        connection.close();

    }
public void delete()throws Exception{
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接,连接数据库
        String url = "jdbc:mysql://localhost:3306/day01";
        String name = "root";
        String password = "zsy20040820";
        Connection connection = DriverManager.getConnection(url, name, password);
        //3.准备sql语句
        String sql = "DELETE FROM `user` WHERE uid = 2";
        //4.获取执行平台Connection中的方法:
        //            Statement createStatement()
        Statement st = connection.createStatement();
        //5.执行sql:Statement中的方法
        //int executeUpdate(String sql) -> 针对于增删改操作的
        int i = st.executeUpdate(sql);
        System.out.println("i = " + i);
        //6.由于增删改不需要处理结果集,所以直接关闭资源
        st.close();
        connection.close();
    }
public void update()throws Exception{
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接数据库
        String url = "jdbc:mysql://localhost:3306/day01";
        String name = "root";
        String password = "zsy20040820";
        Connection connection = DriverManager.getConnection(url, name, password);
        //3.准备sql语句
        String sql = "UPDATE`user` SET username = '刘涛' WHERE uid = 3";
        //4.获取执行平台
        Statement st = connection.createStatement();
        //5.执行
        int i = st.executeUpdate(sql);
        System.out.println("i = " + i);
        //6.由于增删改不需要处理结果集,所以直接关闭资源
        st.close();
        connection.close();
    }
public void select()throws Exception{
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接数据库
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/day01", "root", "zsy20040820");
        //3.准备sql语句
        String sql = "SELECT * FROM `user`";
        //4.获取执行平台
        Statement st = connection.createStatement();
        //5.执行
        ResultSet rs = st.executeQuery(sql);
        //6.处理结果集
        while (rs.next()){
            //String getString(String columnLabel)  -> 获取指定列名的数据
            //int getInt(String columnLabel) -> 获取指定列名的数据
            //String getString(int columnIndex)  -> 获取第几列的数据
            //int getInt(int columnIndex)  -> 获取第几列的数据
            int uid = rs.getInt("uid");
            System.out.println("uid = " + uid);
            String username = rs.getString(2);
            System.out.println("username = " + username);
            int password = rs.getInt("password");
            System.out.println("password = " + password);
        }
        //7.关闭资源
        rs.close();
        st.close();
        connection.close();

    }

由于重复性代码太多于是可以抽取工具类进行代码改进(这里用到了结合properties文件实现)

public class JDBCUtils {
    private static String url = null;
    private static String name = null;
    private static String password = null;

    static {
        try {
            Properties properties = new Properties();
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.propertites");
            properties.load(in);
            Class.forName(properties.getProperty("driverclass"));
            url = properties.getProperty("url");
            name = properties.getProperty("name");
            password = properties.getProperty("password");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, name, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void close(Connection conn, ResultSet rs, Statement st) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

4.使用PreparedStatement预处理对象

概述:PreparedStatement extends Statement

获取:Connection中的方法

PreparedStatement prepareStatement(String sql)

方法:

void setObject(int parameterIndex, Object x)//为?赋值
parameterIndex:指定第几个?
x:为?赋的值
int executeUpdate() //针对增删改操作的
ResultSet executeQuery()  //针对于查询

具体使用场景:

public class Demo05PreparedStatement {
    public static void main(String[] args) throws SQLException {
        //1.创建scannner对象,键入用户和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String password = sc.nextLine();
        //2.连接数据库
        Connection conn = JDBCUtils.getConn();
        //3.准备sql
        String sql = "select * from user where username = ? and password = ?";
        //4.获取执行平台
        PreparedStatement pst = conn.prepareStatement(sql);
        //5.为?赋值
        pst.setObject(1,username);
        pst.setObject(2,password);
        //6.执行
        ResultSet rs = pst.executeQuery();
        //7.直接判断结果集中有没有数据
        if(rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登陆失败");
        }

    }
}

5.PreparedStatement实现批量添加

public class Demo07Batch {
    public static void main(String[] args)throws Exception {
        //1.获取连接
        Connection conn = JDBCUtils.getConn();
        //2.准备sql
        String sql = "insert into `user`(username,password) values (?,?)";
        //3.获取执行平台
        PreparedStatement pst = conn.prepareStatement(sql);
        //4.为?赋值
        //5.执行
        for (int i = 0; i < 10; i++) {
            pst.setObject(1,"张三");
            pst.setObject(2,"0000"+i);
            //将多条语句写入内存中
            pst.addBatch();
        }
        //将多条语句一起打包发送给mysql批量执行
        pst.executeBatch();
        //6.关流
        JDBCUtils.close(conn,null,pst);
    }
}

1.在设置完所有要添加的参数,调用PreparedStatement中的addBatch(),将SQL语句添加到PreparedStatement中

2.调用PreparedStatement中的executeBatch()方法批处理sql语句

6.改造JDBC工具类_结合Properties文件

driverclass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/day01
name=root
password=root
static {
    try {
        Properties properties = new Properties();
        InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.propertites");//自动扫描resource下的文件(可以简单理解为扫描out路径下的配置文件) 
        properties.load(in);//将流中的数据加载到集合中
        Class.forName(properties.getProperty("driverclass"));//获取Class对象
        url = properties.getProperty("url");
        name = properties.getProperty("name");
        password = properties.getProperty("password");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

以上代码是利用了类加载器

ClassLoader classLoader = 当前类.class.getClassLoader()
InputStream in = classLoader.getResourceAsStream("文件名称");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值