java使用原生MySQL实现数据的增删改查以及数据库连接池技术

一、工具类及配置文件准备工作

1.1 引入 jar 包

使用原生 MySQL,只需要用到 MySQL 连接的 jar 包,maven 引用方式如下:

       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>

1.2 jdbc.properties 文件配置

在 resources 文件夹根目录,新增 jdbc.properties 配置文件,内容如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
user=root
password=123456

1.3 JDBCUtils 工具类

在 java 文件夹中新增 util --> JDBCUtils.java 类,该类中获取 jdbc.properties 中的值。

JDBCUtils 工具类主要作用是简化获取 MySQL 配置文件、关闭资源。

    private static String url;
    private static String user;
    private static String password;
</span><span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)"> {
    Properties properties </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Properties();
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
        properties.load(Mytest.</span><span style="color: rgba(0, 0, 255, 1)">class</span>.getClassLoader().getResourceAsStream("jdbc.properties"<span style="color: rgba(0, 0, 0, 1)">));
        url </span>= properties.getProperty("url"<span style="color: rgba(0, 0, 0, 1)">);
        user </span>= properties.getProperty("user"<span style="color: rgba(0, 0, 0, 1)">);
        password </span>= properties.getProperty("password"<span style="color: rgba(0, 0, 0, 1)">);
        Class.forName(properties.getProperty(</span>"driver"<span style="color: rgba(0, 0, 0, 1)">));
    } </span><span style="color: rgba(0, 0, 255, 1)">catch</span> (IOException |<span style="color: rgba(0, 0, 0, 1)"> ClassNotFoundException e) {
        e.printStackTrace();
    }
}
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 1.获取jdbc.properties配置文件中的数据库连接</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> Connection getConnection() <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> SQLException {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> DriverManager.getConnection(url, user, password);
}
</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 5.定义关闭资源的方法</span>
<span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> close(Connection conn, Statement stmt, ResultSet rs) {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (rs != <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
            rs.close();
        } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (SQLException e) {}
    }
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (stmt != <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
            stmt.close();
        } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (SQLException e) {}
    }
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (conn != <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
            conn.close();
        } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (SQLException e) {}
    }
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> close(Connection conn, Statement stmt) {
    close(conn, stmt, </span><span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">);
}</span></pre>

二、原生 MySQL 实现增删改查

2.1 语法说明 

1、通过 Connection 获取数据库连接对象;

2、定义 sql 语句(一般可以在 Navicat 中直接执行);

3、通过获取执行 sql 的对象 --PreparedStatement;

4、执行 sql 语句:增删改使用 conn 的 executeUpdate 方法(成功返回值为 int=1),查询使用 executeQuery 方法 (返回值为 ResultSet,建议使用下文的查询方法操作);

5、释放资源(执行 SQL 时定义的 stmt、获取连接时的 conn)。

2.2 新增数据 -- insertUser()

在 java 文件夹中新增 MyService.java 类,将获取数据库连接抽取出来,方法如下:

    private Connection conn;
    {
        try {
            conn = JDBCUtils.getConnection();} catch (SQLException e) {e.printStackTrace();
        }
    }

在 MyService.java 类中新增 insertUser 方法,具体如下

String sql = "INSERT INTO user values (4,' 腾讯科技 ','xinfeng37812','2009-11-16',' 广东省深圳市 ')";
PreparedStatement  stmt = conn.prepareStatement(sql);
int count = stmt.executeUpdate(sql);
JDBCUtils.close(conn, stmt);
return count;

2.2 修改数据 -- updateById()

String sql = "update user set password = 567875 where id = 2";
PreparedStatement stmt = conn.prepareStatement(sql);
int count = stmt.executeUpdate(sql);
JDBCUtils.close(conn, stmt);
return count;

2.3 删除数据 -- deleteUser()

String sql = "delete from user where id = 5";
PreparedStatement  stmt = conn.prepareStatement(sql);
int count = stmt.executeUpdate(sql);
JDBCUtils.close(conn, stmt);
return count;

2.4 查询数据 -- findAll()

前提:新建 entity --> User.java 实体类,并获取 getter&setter、toSting 方法;

        String sql = "select * from user";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet count = stmt.executeQuery(sql);
        User user = null;
        List<User> arr = new ArrayList<>();
        while(count.next()){
            Long id = count.getLong("id");
            String username = count.getString("username");
            String password = count.getString("password");
            Date birthday = count.getDate("birthday");
            String address = count.getString("address");
            user = new User();
            user.setId(id);
            user.setUsername(username);
            user.setPassword(password);
            user.setBirthday(birthday);
            user.setAddress(address);
            arr.add(user);
        }
        JDBCUtils.close(conn, stmt, count);
        return arr;

三、原生 MySQL 语句的缺点及数据库连接池

3.1 原生 MySQL 语句的缺点

1、每一次查询都要新增通道,关闭通道,效率太低。实际项目中都会用数据库连接池进行优化;

2、实际项目中使用最多的就是查询,但是将查询的 ResultSet 结果,进行封装的代码过于臃肿。

3.2 c3p0 和 druid 连接池技术

数据库连接池其实就是一个容器,在 java 中,使用 getConnection 方法代替 Connection,实现节约资源,用户访问高效目的,但是代码本身与原生并无本质的减少。

3.2.1 c3p0 使用

需要导入两个 jar 包,maven 引用方式如下:

<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.5</version>
</dependency>
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>mchange-commons-java</artifactId>
    <version>0.2.15</version>
</dependency>

配置文件必须在 resources 文件夹根目录,且名称必须为 c3p0.properties 或者 c3p0-config.xml,因此无需手动加载配置文件:

 //1. 创建数据库连接池对象
DataSource ds  = new ComboPooledDataSource();
//2. 获取连接对象
Connection conn = ds.getConnection();

3.2.2 druid 使用

只需要一个 jar 包,maven 引入方式如下:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>

配置文件名称任意,但需要是.properties 形式的,因此需要获取配置文件位置,具体使用方式如下:

//1. 加载配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//2. 获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//3. 获取连接
Connection conn = ds.getConnection();

3.3 JDBCUtils 工具类的改造

以使用 druid 为例,在使用数据库连接池时的工具类,主要有三种方法:

1. 获取连接方法:通过数据库连接池获取连接
2. 释放资源
3. 获取连接池的方法

public class JDBCUtils {
  private static DataSource ds;
  static {
    try {
      Properties pro = new Properties();
      pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
      ds = DruidDataSourceFactory.createDataSource(pro);
    } catch (IOException e) {e.printStackTrace();
    } catch (Exception e) {e.printStackTrace();
    }
  }

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

public static void close(Statement stmt, Connection conn) {
close(
null, stmt, conn);
}

public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
// 归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public static DataSource getDataSource() {
return ds;
}
}