【Java+JDBC+MySQL】使用Java操作JDBC连接MySQL数据库

22 篇文章 1 订阅
3 篇文章 1 订阅

1. 导入jar包

将jar拷贝到lib目录,右键jar包-【Add as Library】导入项目中
在这里插入图片描述

2 操作步骤(加,连,语,执,释)

2.1 加载注册驱动

通过下述语句实现注册驱动,原理是这句语句会将 Driver.class 这份字节码加载到 JVM 中,然后 JVM 会执行该字节码的静态代码块,mysql 提供的这个驱动包中,Driver 的字节码内的静态代码块就完成了驱动对象的创建和注册。

//加载注册驱动
Class.forName("com.mysql.jdbc.Driver");

2.2 连接数据库

当我们注册了驱动之后,可以通过 DriverManager 获取与数据库的连接,需要传入三个参数:数据库的地址,登录用户名,登陆密码。注意 Connection 和 DriverManager 类都是 java.sql 包下的,dbName 是数据库的名字。

//连接数据库
Connection conn = DriverManager.getConnection(jdbc:mysql://localhost:3306/dbName", "root", "123");

验证已经获取连接,可以在 mysql 控制台,使用命令:show processlist 查看运行进程。

2.3 创建语句对象

当得到与数据的连接之后,我们还需要通过该连接获得一个语句对象,该语句对象内包含我们要对数据库执行的操作,也就是 SQL 语句。

 // 创建语句对象
 Statement statement = connection.createStatement();

2.4 执行语句

我们执行 SQL 语句一般使用语句对象的 executeUpdate 和 executeQuery 方法,前者用于 DDL 和 DML 操作,返回收影响的行数;后者用于执行 DQL 操作,返回结果集对象。具体使用方法如下:

// 4.执行sql语句
String sql = "create table t_student1 (id int primary key auto_increment, name varchar(20), age int)";
int state = statement.executeUpdate(sql);

2.5 释放资源

// 释放资源
statement.close();
connection.close();

总结:加,连,语,执,释

package com.henu.demo.core;
import java.sql.*;

public class JdbcTest {

    public static void main(String[] args) throws Exception {
        String sql = "create table t_student1 (id int primary key auto_increment, name varchar(20), age int)";
        // 1. 加载注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2.获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "pangpd", "123123");
        // 3.创建语句对象
        Statement statement = connection.createStatement();
        // 4.执行sql语句
        int state = statement.executeUpdate(sql);
        // 5. 释放资源
        statement.close();
        connection.close();
    }
}

3. 代码重构

在 2.4 中示范了怎么连接数据库进行一次建表操作,实际上 DAO 中的实现类内就是一个个这样的方法,比如常见的增、删、改、查,如果每个方法内都写这样一些列流程,会在后期维护中产生很大麻烦,假如连接密码改了,每个方法都要修改,这显然不现实,所以我们要利用工具类以及配置文档优化代码。

实现类中的方法应该专注于功能的实现,获得连接是该方法需要的一个结果,该方法并不关注这个过程,不应该放在方法内混淆语义。我们可以把连接数据库的代码放在 JdbcUtils 这个工具类内,该类的成员都是类成员,然后实现类的方法中直接通过类调用 getConnection() 方法获得连接。同时,注册驱动这个步骤我们只需要执行一次就够了,我们可以把这个步骤放在工具类的静态代码块中,在该类初始化的时候会自动执行一次。

3.1 抽方法JdbcUtils(加载注册驱动,获取连接对象,关闭资源)

package com.henu.demo.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils {

    private static String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
    private static String user = "pangpd";
    private static String password = "123123";

    // 加载注册驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    // 获取连接对象
    protected static Connection getConnection() throws Exception {

        Connection connection = null;
        connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    // 关闭资源
    protected static void colse(Connection connection, Statement statement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                statement = null;
            }
        }
    }
}

3.2 抽出连接需要的信息(jdbc.properties)

把连接需要的这些信息放在代码块中还是不太方便,如果用户修改了账号密码,或者主机地址改变,都需要重新修改代码,这不太满足我们平常应用的要求。所以我们可以把这些信息放在一个 .properties 文件中,Java 程序直接去读取这些信息。那以后修改了账户密码,只需要自己打开这个.properties文件修改相应的字段即可。

#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbc_demo
username=root
password=123123

.properties 内存放了一些键值对,注意等号左右没有空格,结尾也没有标点,# 作为注释

3.2.1 读取.properties文件

Java 中通过类加载器读取配置文件获得一个输入流,可以通过两种方法获得类加载器:

//1.通过某一类的字节码实例可以获取
ClassLoader cl = Object.class.getContextClassLoader();

//2.通过当前线程获得
ClassLoader cl = Thread.currentThread().getContextClassLoader();
//通过类加载器读取配置文件获得输入流
InputStream in = cl.getResourceAsStream("jdbc.properties");

那如何获得相应的信息呢?

我们可以通过 Properties 对象获得相应的信息。Properties 类是 Map 抽象类下一个专门用于读取配置文件的类,将输入流加载进去,即可通过“key”获得“value”。

Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("driverClassName"));

3.2.2 重构后的JdbcUtils

package com.henu.demo.core;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils2 {
    private static Properties p = new Properties();

    // 加载注册驱动
    static {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream in = cl.getResourceAsStream("jdbc.properties");

        try {
            p.load(in);
            Class.forName(p.getProperty("driverClass"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接对象
    protected static Connection getConnection() throws Exception {

        Connection connection = null;
        connection = DriverManager.getConnection(p.getProperty("url"), p.getProperty("user"), p.getProperty("password"));
        return connection;
    }

    // 关闭资源
    protected static void colse(Connection connection, Statement statement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                statement = null;
            }
        }
    }
}

4. 引入连接池(Druid),管理连接

按照上面的做法,每次用户进行一次操作,都会建立连接,接着执行完成后销毁连接。虽然每次连接、断开连接用时不长,但当用户数量上来意后,对系统资源的消耗就会变得很高。于是我们引入连接池管理连接。连接池里面拥有一定数量的连接(一般5 - 10个),当通过连接池getConnection 时,连接池提供一个连接供方法使用,当使用完毕后方法执行连接的 close 方法,这个时候并不是直接关闭连接,而是将连接返回给连接池。

在Java中,连接池使用 javax.sql.DataSource 接口来表示连接池。

注意:DataSource 仅仅只是一个接口,由各大服务器厂商来实现。常用的 DataSource 的实现:

在Java中,连接池使用 javax.sql.DataSource 接口来表示连接池。注意:DataSource 仅仅只是一个接口,由各大服务器厂商来实现。常用的 DataSource 的实现:

  • DBCP: Spring推荐的
  • C3P0: Hibernate推荐的
  • Druid : (德鲁伊)阿里巴巴开源的,性能最好,速度最快

4.1Druid 使用方法

方法一:

//需要导入 Druid 的 jar 包
//方法一:
//1 创建连接池对象,不能使用 DataSource 类型,因为 setXxx 方法时 DruidDataSource 类独有的
DruidDataSource dds = new DruidDataSource();
//2 设置连接数据库的信息
dds.setDriverClassName(p.getProperty("driverClassName"));
dds.setUrl(p.getProperty("url"));
dds.setUsername(p.getProperty("username"));
dds.setPassword(p.getProperty("password"));
dds.setMaxActive(10);  //最大连接数
Connection conn = dds.getConnection();

方法二:
//通过连接池工程获得连接池

//1 通过工厂的静态方法获得连接池,传入上文中的 Properties 对象作为参数,工程自动读取配置信息
DataSource ds = DruidDataSourceFactory.createDataSource(p);
//2 获得连接
Connection conn = ds.getConnection();

4.2 使用Druid后的工具类

package com.henu.demo.core;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils3 {
    private static Properties properties = new Properties();
    private static DataSource dataSource = null;

    // 加载注册驱动
    static {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream in = cl.getResourceAsStream("jdbc.properties");

        try {
            properties.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接对象
    protected static Connection getConnection() throws Exception {

        Connection connection = null;
        connection = dataSource.getConnection();
        return connection;
    }

    // 关闭资源
    protected static void colse(Connection connection, Statement statement) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                statement = null;
            }
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值