0%

jdbc练习

说明

  • 本次主要针对jdbc的知识点进行练习,用到了maven,mysql,idea等知识点

  • 本次的java版本如下

1
2
3
4
C:\Users\Administrator>java -version
java version "1.8.0_381"
Java(TM) SE Runtime Environment (build 1.8.0_381-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.381-b09, mixed mode)

配置

  • 在IDEA里新建一个maven项目,项目名叫做:MavenMysqlJdbc

  • 本地win搭建好mysql服务,本次搭建的的版本为:8.0.13

  • 打开src下的pom.xml文件, 在里面添加Mysql的jdbc包的引用,代码如下

1
2
3
4
5
6
7
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>
  • 自动下载依赖文件中,可能出现卡死,需要maven的内存:-Xms1024m -Xmx2048m修改如下:

image-20231115174256836

反射properties

  • 新建数据库配置文件,获取配置文件信息后,再注册数据库驱动,在src——main——resources目录下,新建db.properties文件
1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
user=root
password=123456
  • 新建util包,然后在里面创建JdbcUtil类,利用反射获取db.properties文件信息,最后返回数据库连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package util;

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

public class JdbcUtil {
private static String driver;
private static String url;
private static String user;
private static String pwd;

static {
try{
Properties properties = new Properties();
// 通过反射,新建字符输入流,读取db.properties文件
InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
// 输入流中读取到的属性,加载到properties属性集对象中
properties.load(inputStream);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
pwd = properties.getProperty("password");


} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
// 注册数据库驱动
Class.forName(driver);
//获取数据库连接(里面内容依次是:主机名和端口、用户名、密码),返回数据库链接
return DriverManager.getConnection(url,user, pwd);
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e);
}
}
}

  • 在java(src-main-java)目录下创建LinkMysql类,调用JdbcUtil类返回的数据库连接操作数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import util.JdbcUtil;
public class LinkMysql {
public static void main(String[] args) throws SQLException {
// 获取数据库链接
Connection connection = JdbcUtil.getConnection();
//需要执行的sql语句
String sql = "insert into class(name,sex) values(?,?)";
///获取预处理对象,并给参数赋值
PreparedStatement statement = connection.prepareCall(sql);
statement.setString(1, "刘亦菲");
statement.setString(2, "女");
//执行sql语句(插入了几条记录,就返回几)
int num = statement.executeUpdate();
System.out.println(num);

// 删除数据
String sql1 = "delete from class where id=17";
PreparedStatement statement1 = connection.prepareCall(sql1);
int num1 = statement1.executeUpdate();
System.out.println(num1);
// 关闭sql链接
statement.close();
connection.close();
}
}


ResourceBundle类获取properties

  • 在util包里面创建创建JdbcUtil2类,ResourceBundle类获取db.properties文件信息,最后返回数据库连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package util;

import java.sql.*;
import java.util.ResourceBundle;

public class JdbcUtil2 {
private static String url;
private static String user;
private static String pwd;

static {
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle("db");
url = resourceBundle.getString("url");
pwd = resourceBundle.getString("password");
user = resourceBundle.getString("user");
} catch (Exception e) {
throw new RuntimeException(e);
}
}


public static Connection getConnection() {
try {
//获取数据库连接(里面内容依次是:主机名和端口、用户名、密码),返回数据库链接
return DriverManager.getConnection(url,user, pwd);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

// 关闭结果集
public static void closeResultSet(ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
// 关闭预处理对象
public static void closeStatement(Statement statement) throws SQLException {
if (statement != null) {
statement.close();
}
}
// 关闭数据库连接
public static void closeConnection(Connection connection) throws SQLException {
if (connection != null) {
connection.close();
}
}
// 关闭如上三个
public static void closeResource(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
closeResultSet(resultSet);
closeStatement(statement);
closeConnection(connection);
}
}

  • 在java目录下创建LinkMysql2类,调用JdbcUtil2类返回的数据库连接操作数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import util.JdbcUtil2;

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

public class LinkMysql2 {
public static void main(String[] args) throws SQLException {
// 获取数据库链接
Connection connection = JdbcUtil2.getConnection();
//需要执行的sql语句
String sql = "insert into class(name,sex) values(?,?)";
///获取预处理对象,并给参数赋值
PreparedStatement statement = connection.prepareCall(sql);
statement.setString(1, "刘亦菲");
statement.setString(2, "女");
//执行sql语句(插入了几条记录,就返回几)
int num = statement.executeUpdate();
System.out.println(num);

// 删除数据
String sql1 = "delete from class where id=17";
PreparedStatement statement1 = connection.prepareCall(sql1);
int num1 = statement1.executeUpdate();
System.out.println(num1);
// 关闭sql链接
JdbcUtil2.closeResource(null, statement, connection);
}
}

DButils工具包

  • 打开src下的pom.xml文件, 在里面添加DButils的引用,代码如下
1
2
3
4
5
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.5</version>
</dependency>
  • 创建src-java-main-Dbutils类,往数据库内进行增删改查据,代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import util.JdbcUtil2;

import java.sql.Array;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class Dbutils {

public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
String sql = "insert into class(name,sex) values(?,?)";
Object[] object = {"自然", "男"};
Connection connection = JdbcUtil2.getConnection();
// 增加
int num = queryRunner.update(connection,sql,object);

System.out.println("新增数据行:" + num);

String updateSql = "update class set name=? where id=?";
Object[] object2 = {"自然2", 20};
// 修改
int num2 = queryRunner.update(connection,updateSql,object2);
System.out.println("修改数据行:" + num2);

String delSql = "delete from class where id=?";
Object[] object3 = {20};
// 删除
int num3 = queryRunner.update(connection,delSql,object3);
System.out.println("删除行:"+num3);

String sqlSelect = "select * from class";
// 执行查询,并以数组的形式返回查询结果(new ArrayHandler()只会返回第一条记录)
Object[] objects = queryRunner.query(connection,sqlSelect,new ArrayHandler());
System.out.println("单行查询结果:" + Arrays.toString(objects));
System.out.println("\n");
//执行查询,并以数组的形式返回查询结果(new ArrayListHandler()返回所有查询到的记录)
List<Object[]> lists = queryRunner.query(connection,sqlSelect,new ArrayListHandler());
for(Object[] item: lists) {
System.out.println("多行查询:" + Arrays.toString(item));
}
connection.close();
}
}

转换为实体

  • 新建一个表的实体类,src-java-main-Classs(当初我新建这个表瞎编的。。。)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Classs {
private int id;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
@Override
public String toString() {
return "class:id" + id +"name:" + name + "sex:" + sex;
}
}

  • 新建一个src-main-java-DbutilsBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.JdbcUtil2;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class DbutilsBean {
public static void main(String[] args) throws SQLException {
//创建dbUtils里面的QueryRunner对象
QueryRunner queryRunner = new QueryRunner();
Connection connection = JdbcUtil2.getConnection();

String sqlSelect = "select * from class";
// 执行查询,并以数组的形式返回查询结果(new BeanHandler()只会返回第一条记录,并转成对象)
Classs classs = queryRunner.query(connection,sqlSelect,new BeanHandler<Classs>(Classs.class));
System.out.println("单行查询结果:" + classs);

System.out.println("\n");
//执行查询,并以数组的形式返回查询结果(new BeanListHandler()返回查询到的所有记录,并转成对象)
List<Classs> lists = queryRunner.query(connection,sqlSelect,new BeanListHandler<Classs>(Classs.class));
for(Classs item: lists) {
System.out.println("多行查询:" + item.getName());
}
System.out.println(lists);
connection.close();
}
}

  • 得到结果
1
2
3
4
多行查询:综艺一般
多行查询:五年一班
多行查询:王大炮
多行查询:刘大师
  • 更多用法
1
2
3
4
5
6
7
8
9

String sql = "select * from stu where age>?";
...
Object[] params = {16};
// 会返回结果中指定的列,比如返回name
List<Object> strs = queryRunner.query(connection,sql, new ColumnListHandler<>("name"),params);
//查询单数据
int age = queryRunner.query(connection,sql, new ScalarHandler<>(),params);
System.out.println(age);

连接池

  • 在scr——pom.xml文件里,引入c3p0包
1
2
3
4
5
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
  • 在src——main——resources下增加c3p0-config.mxl文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai</property>
<property name="user">root</property>
<property name="password">123456</property>
<!-- 扩展配置 -->
<!-- 获取连接超时设置,默认是一直等待,单位毫秒 -->
<property name="checkoutTimeout">30000</property>
<!--每多少秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod">30</property>
<!-- 初始化连接池的连接数 -->
<property name="initialPoolSize">10</property>
<!--最大空闲时间,多少秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime">30</property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize">100</property>
<!-- 连接池中保留的最小连接数 -->
<property name="minPoolSize">10</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default:0 -->
<property name="maxStatements">200</property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection">200</property>
<!--c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能 通过多线程实现多个操作同时被执行。Default:3 -->
<property name="numHelperThreads">3</property>
</default-config>
</c3p0-config>
  • 在src——main——java——util里添加DataSourceUtils类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package util;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;

public class DataSourceUtils {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

/**
* 获取数据源
* @return 连接池
*/
public static DataSource getDataSource() {
return dataSource;
}
}

  • 新建src-main-java-C3p0Select类,用数据库连接池的方式查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

public class C3p0Select {

public static void main(String[] args) throws SQLException {
// 创建dbUtils里面的QueryRunner对象,并获取数据库连接
QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());
// String sqlSelect = "select * from class where id>?";
String sqlSelect = "select * from class";
Object[] params = {16};

//执行查询,并以数组的形式返回查询结果(new BeanListHandler()返回查询到的所有记录,并转成对象)
// List<Classs> lists = queryRunner.query(sqlSelect,new BeanListHandler<Classs>(Classs.class), params);
List<Classs> lists = queryRunner.query(sqlSelect,new BeanListHandler<Classs>(Classs.class));
for(Classs item: lists) {
System.out.println("多行查询:" + item.getName());
}
System.out.println(lists);
}
}

  • 得到结果
1
2
3
4
多行查询:综艺一般
多行查询:五年一班
多行查询:王大炮
多行查询:刘大师

注意

  • 此练习代码主要来自这里