JDBC学习笔记

JDBC使用

数据库连接的各个对象

  • DriverManager:驱动管理对象

    • 注册驱动: DriverManager.registerDiver(Driver driver);
    • 获取数据库连接:
      1
      Connection connector = DriverManager.getConnection("jdbc:mysql://localhost:3306/xby?serverTimezone=GMT","root","xby123456");
  • Connection:数据库连接对象

    • 获取执行sql语句的对象:
      • Statement createStatement(String sql);
      • PreparedStatement prepareStatement(String sql);
    • 管理事务
      • 开启事务: void setAutoCommit(boolean autoCommit); 调用该方法,若设置参数为false,即设置手动提交开启事务.
      • 提交事务: void commit();
      • 回滚事务: void rollback();
  • Statement:执行sql语句对象

    • boolean execute(String sql);执行任意的sql语句
    • int executeUpdate(String sql);执行DML,DDL语句,返回一个整数代表sql语句影响数据库的行数
    • ResultSet executeQuery(String sql);执行DQL语句
  • ResultSet:结果集对象

    • boolean next():游标向下移动一行,判断当前行是否是最后一行末尾,如果是,则返回false
    • getXXX(参数):获取数据,参数代表列的序号

JDBC获取数据库连接的步骤
-
1.注册驱动: Class.forname(“驱动地址”);

2.获取数据库连接对象:Connection coon=DriverManager.getConnection(数据库url地址,数据库用户名,数据库用户密码);

(此时已经获取到了数据库的连接对象)

3.使用数据库连接对象获取执行sql语句的对象:Statement sta=coon.createStatement();

4.写好sql语句并使用获取到的执行sql语句对象执行sql语句:sta.execute();

数据库的查询遍历

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
import java.sql.*;

class abc
{
public static void main(String[] args)
{
Connection connector = null;
Statement str= null;
int num = 0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connector = DriverManager.getConnection("jdbc:mysql://localhost:3306/xby?serverTimezone=GMT","root","xby123456");
String sql="select *from money";
str = connector.createStatement();
ResultSet res = str.executeQuery(sql);
while(res.next())
{
System.out.println("id:"+res.getInt(1)+" name:"+res.getString(2)+" balance "+res.getInt(3));
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
} catch (SQLException e)
{
e.printStackTrace();
} finally
{
try {
str.close();
connector.close();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(num+" lines are infuluced");
}
}
}
  • PreparedStatement:执行sql对象,与Statement不同的是,PreparedStatement是预处理对象,安全性更高.
    • 新建PreparedStatement对象时要将sql语句作为参数传进去,sql语句中也要使用占位符,然后再设置占位符对应的数据,再进行执行

事务的操作

1.事务的开启:conn.setAutoCommit(false);
传入的参数为false,关闭自动提交,此时就开启了事务.

2.事务的提交:conn.commit();

3.事务的回滚:conn.rollback();

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
public static void main(String[] args)
{
Connection connector=null;
String sql1="update money set balance=balance+? where id = ?";
String sql2="update money set balance=balance-? where id = ?";
PreparedStatement pre1= null;
PreparedStatement pre2=null;
try {
connector= JDBCUtils.getConnection("jdbc:mysql://localhost:3306/xby?serverTimezone=GMT","root","xby123456");
connector.setAutoCommit(false);
pre1=connector.prepareStatement(sql1);
pre2=connector.prepareStatement(sql2);
pre1.setInt(1,500);
pre1.setInt(2,1);
pre2.setInt(1,500);
pre2.setInt(2,2);
int num1= pre1.executeUpdate();
int num2 = pre2.executeUpdate();
int num=num1+num2;
System.out.println(num+" lines are influenced");
connector.commit();
}
catch (SQLException e)
{
try {
connector.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
finally {
try {
connector.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

数据库连接池:

每次获取连接时申请资源很耗时,用容器将获取好的连接存起来,访问时,从连接池中获取连接,用完后再还回去,这种操作十分高效.

c3p0
-

1:导包

导入c3p0.jar, mchange-commons.jar和mysql的jar包.

2.配置文件

配置文件 c3p0-config.xml

3.代码

通过ComboPooledDataSource()来创建DataSource对象.

DataSource()相当于连接源,每次获取连接,都通过DataSource()来获取.

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args)
{
DataSource ds = new ComboPooledDataSource();
System.out.println("hello wrold");
for (int i = 1; i <=5 ; i++) {
try {
Connection connector = ds.getConnection();
System.out.println(i+":"+connector.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
}

德鲁伊Druid
-
1.导包

导入druid.jar 与 mysql的jar包即可

2.配置文

配置文件名为 druid.properties

3.代码

在druid中,连接源DataSource变成通过DruidDataSourceFactory的createDataSource()方法来创建.

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args)
{
Properties pro=new Properties();
InputStream in = DruidPool.class.getClassLoader().getResourceAsStream("druid.properties");
try {
pro.load(in);
DataSource ds= DruidDataSourceFactory.createDataSource(pro);
Connection con=ds.getConnection();
System.out.println(con);
} catch (Exception e) {
e.printStackTrace();
}
}

Template
-
1.导包

导入Template的五个jar包

2.获取DataSource对象

通过数据库连接池获取DataSource对象

3.获取JdbcTemplate对象

通过JdbcTemplate传入DataSource来获取JdbcTemplate对象

4.代码

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args)
{
JdbcTemplate template=new JdbcTemplate(DruidUtils.getSource());
String sql="select * from money";
List<Map<String, Object>> maps = template.queryForList(sql);
for(Map map:maps)
{
System.out.println( map);
}
}

JdbcTemplate的方法
-
1.template.update()

执行sql语句,返回一个整数,代表sql语句影响数据库的行数

2.template.queryForMap()

执行sql的查语句,返回一个Map类型的集合,集合中列名最为key,查询到的值作为value,一一对应.该方法只能查询一行数据

3.template,queryForList()

执行查语句,可以查多行数据,返回的是一个List集合,集合中装的是每一行数据封装的Map集合.

4.template.query()

将查询到的数据封装成一个对象.

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args)
{
JdbcTemplate template=new JdbcTemplate(DruidUtils.getSource());
String sql="select * from money";
List<person> personList = template.query(sql, new BeanPropertyRowMapper<person>(person.class));
for(person p:personList)
{
System.out.println(p);
}
}

5.template.queryForObject()

执行查询,将结果封装成指定的对象.

template.queryForObject(sql,想要封装的对象.class)

1
2
3
4
5
6
7
public static void main(String[] args)
{
JdbcTemplate template=new JdbcTemplate(DruidUtils.getSource());
String sql="select count(id) from money";
Integer num = template.queryForObject(sql, Integer.class);
System.out.println(num);
}