Java JDBC (MySQL5.7)

第一章 JDBC简介

  • Java DataBase Connection,一套Java操作数据库的接口的规范
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OtnR2xpM-1648709008358)(img\jdbc连接数据库.bmp)]

1. JDBC的好处

  • 我们只需要会调用JDBC接口中的方法即可,使用简单
  • JDBC有关的类和接口:都在java.sql 和 javax.sql(扩展包) 包下
  • 方法体由具体的数据库厂商来完成的
  • 使用同一套Java代码,进行少量的修改就可以访问其他JDBC支持的数据库

第二章 JDBC使用

1. 使用步骤:

  1. 下载MySQL for Java 驱动 Maven仓库,add as library
  2. 加载驱动
  3. 建立连接
  4. 编写SQL语句
  5. 创建执行sql的Statement对象,执行sql(增删改查)
  6. 最后关闭资源,statement、connection、resultSet.

2. 普通方式实现代码

package mysql_use;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class Demo01 {

    public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
        conMySQL();//使用 PreparedStatement 预编译sql
        conMySQL2();//使用 Statement
    }

    //使用 PreparedStatement 预编译sql
    public static void conMySQL() throws SQLException, ClassNotFoundException, IOException {
        //1.从配置文件中读取 连接配置,用户名,密码
        Properties dbConfig = getProperties();
        String driverClassName = dbConfig.getProperty("driverClassName");com.mysql.cj.jdbc.Driver
        String url = dbConfig.getProperty("url");//jdbc:mysql://ip:3306/数据库名
        String username = dbConfig.getProperty("username");//MySQL数据库用户名
        String password = dbConfig.getProperty("password");//MySQL数据库密码

        //2.加载驱动类 com.mysql.cj.jdbc.Driver类,
        //实际是为了执行Driver类中的静态代码块{ DriverManager.registerDriver(new Driver()); }注册MySQL驱动
        Class.forName(driverClassName);

        //3.建立连接,给定参数(某个数据库,用户名,密码)
        Connection connection = DriverManager.getConnection(url, username, password);

        //4.编写sql语句
        String user = "root";//模拟传入的用户名
        String pwd = "123456";//模拟传入的密码
        String sql = "select * from emp where username = ? and password = ?";// ?占位符,具体内容先不写,由PreparedStatement对象.setXX()方法 设置

        //4.创建 预编译SQL语句的PreparedStatement对象 ( 防止SQL注入风险,提高PerparedStatement对象的复用性)
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, user);//第一个?占位符 用usen值替换
        preparedStatement.setString(2, pwd);  //第二个?占位符 用pwd值替换

        //5. 执行sql,得到结果集
        ResultSet resultSet = preparedStatement.executeQuery();

        //6. 打印结果
        while (resultSet.next()) { //next() 初始指向 row 0 字段栏 ,方法执行完移动到下一行
            //此时next()指向 row 1
            //根据字段的数据具体类型,返回对应的数据类型
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            double salary = resultSet.getDouble(6);
            double bonus = resultSet.getDouble(7);

            System.out.println("id:" + id);
            System.out.println("name:" + name);
            System.out.println("salary:" + salary);
            System.out.println("bonus:" + bonus);
            System.out.println("=========================");
        }

        //7.关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

    //使用 Statement
    public static void conMySQL2() throws SQLException, ClassNotFoundException, IOException {

        //1.从配置文件中读取 连接配置,用户名,密码
        Properties dbConfig = getProperties();
        String driverClassName = dbConfig.getProperty("driverClassName");
        String url = dbConfig.getProperty("url");
        String username = dbConfig.getProperty("username");
        String password = dbConfig.getProperty("password");

        //2.加载驱动类 com.mysql.cj.jdbc.Driver类,
        //实际是为了执行Driver类中的静态代码块{DriverManager.registerDriver(new Driver());}注册MySQL驱动
        Class.forName(driverClassName);

        //3.建立连接,给定参数(某个数据库,用户名,密码)
        Connection connection = DriverManager.getConnection(url, username, password);

        //4.编写sql语句
        String user = "root";//模拟传入的用户名
        String pwd = "123456";//模拟传入的密码
        String sql = "select * from emp where username = '"+user+"'" + "and password='" + pwd + "'";//登录校验

        //4.创建 执行静态SQL语句的Statement对象
        //或创建 预编译SQL语句的PreparedStatement对象 防止SQL注入风险
        Statement statement = connection.createStatement();

        //5. 执行sql,返回结果集
        ResultSet resultSet = statement.executeQuery(sql);

        //6. 打印结果
        while (resultSet.next()) { //next() 初始指向 row 0 字段栏 ,方法执行完移动到下一行
            //此时next()指向 row 1
            //根据字段的数据具体类型,返回对应的数据类型
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            double salary = resultSet.getDouble(6);
            double bonus = resultSet.getDouble(7);

            System.out.println("id:" + id);
            System.out.println("name:" + name);
            System.out.println("salary:" + salary);
            System.out.println("bonus:" + bonus);
            System.out.println("=========================");
        }

        //7.关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }

    //获取资源文件输入流,并存到Properties集合中
    private static Properties getProperties() throws IOException {
        InputStream inputStream = Demo01.class.getClassLoader().getResourceAsStream("db.properties");
        Properties dbConfig = new Properties();
        dbConfig.load(inputStream);
        return dbConfig;
    }
}

3. 优化为工具类

package mysql_use;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

public class JDBCUtil {

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

    static {
        Properties dbConfig = getProperties();

        try {
            Class.forName(driverClassName); //为了执行Driver类中的静态代码块 注册驱动
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        driverClassName = dbConfig.getProperty("driverClassName");
        url = dbConfig.getProperty("url");
        username = dbConfig.getProperty("username");
        password = dbConfig.getProperty("password");
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //获取资源文件输入流,并存到Properties集合中
    private static Properties getProperties() {
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties dbConfig = new Properties();
        try {
            dbConfig.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dbConfig;
    }
}

4. 使用数据库连接池Druid

package mysql_use;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

public class DruidUtil {

    private static DataSource dataSource;

    static {
        Properties dbConfig = getProperties();
        DruidDataSource druidDataSource = new DruidDataSource();//使用连接池
		//设置 驱动路径、url、用户、密码
        druidDataSource.setDriverClassName(dbConfig.getProperty("driverClassName"));
        druidDataSource.setUrl(dbConfig.getProperty("url"));
        druidDataSource.setUsername(dbConfig.getProperty("username"));
        druidDataSource.setPassword(dbConfig.getProperty("password"));
        dataSource = druidDataSource;
    }

    //获取资源文件输入流,并存到Properties集合中
    private static Properties getProperties() {
        try {
            InputStream inputStream = DruidUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties dbConfig = new Properties();
            dbConfig.load(inputStream);
            if (inputStream != null) inputStream.close();
            return dbConfig;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}

第三章 参考资料

B站黑马程序员

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值