JDBC 学习笔记
学习参考链接:
https://www.bilibili.com/video/BV1Qf4y1T7Hx/?p=30&share_source=copy_web&vd_source=c76bb3d6e0326c966bf1bf32db90eb22
简介
简单来说,JDBC是一种规范,可以通过同一套代码,配合不同数据库驱动实现数据库的操作。
快速入门
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| // 注册驱动 Class.forName("com.mysql.jdbc.Driver");
// 获取连接 String url = "jdbc:mysql://localhost:3306/itheima"; String username = "root"; String password = "123456"; Connection conn = DriverManager.getConnection(url, username, password);
// 定义sql语句 String sql = "insert into account values ('1', '张三' , 2000)";
// 获取执行sql的对象 Statement Statement statement = conn.createStatement();
// 执行sql int count = statement.executeUpdate(sql); // 返回值为受影响的函数值
// 处理结果 System.out.println(count);
// 释放资源 statement.close(); conn.close();
|
事务管理
connection 接口对应的三个方法。
- 开启事务:setAutoCommit(boolean autoCommit); 默认为true,
自动提交
- 提交事务:commit()
- 回滚事务:rollback()
Statement
- int executeUpdate(sql); 执行DML、DDL语句
- ResultSet executeQuery(sql);
执行DQL语句。返回值为查询的结果
参考代码:
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 com.feng.jdbc;
import javax.sound.midi.Soundbank; import java.sql.*;
public class JdbcDemo2 { public static void main(String[] args) throws Exception { String url = "jdbc:mysql://127.0.0.1:3306/learn_jdbc"; String user = "root"; String password = "100228"; Connection conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT * from user;";
Statement stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(sql);
while (res.next()){ int id = res.getInt(1); String name = res.getString(2); int age = res.getInt(3);
System.out.println(id); System.out.println(name); System.out.println(age); System.out.println("***************");
} res.close(); stmt.close(); conn.close(); } }
|
PreparedStatement
预编译sql语句,预防sql注入问题
使用方法:
- String sql = "select * from user where name =
?";
- 参数用?代替。再使用setXxx(参数1,参数2),设置参数。参数1为序号,参数2为填入?的值,索引从1开始。
- conn.prepareStatement(sql);
- executeQuery(); 这里不需要参数
数据连接池 Driud
创建一个配置文件存放配置信息
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| # 数据库驱动 driverClassName=com.mysql.cj.jdbc.Driver # 数据库连接 url=jdbc:mysql: # 数据库用户名 username=root # 数据库密码 password=******* #初始化连接数量 initialSize=5 #最大连接数 maxActive=10 #获取连接最大等待时间 maxWait=3000
|
使用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13
| public static void main(String[] args) throws Exception { Properties prop = new Properties(); prop.load(new FileInputStream("jdbc-demo\\src\\druid.properties")); DataSource dataSource = DruidDataSourceFactory.createDataSource(prop); Connection conn = dataSource.getConnection(); System.out.println(conn); }
|
案例1 - 查看所有数据
已有数据库
1 2 3 4 5 6 7 8
| mysql> select * from tb_brand; +----+------------+----------------------+---------+--------------------------------+--------+ | id | brand_name | company_name | ordered | description | status | +----+------------+----------------------+---------+--------------------------------+--------+ | 1 | 三只松鼠 | 三只松鼠股份有限公司 | 5 | 好吃不上火 | 0 | | 2 | 华为 | 华为技术有限公司 | 100 | 华为致力于把数字世界带入每个人 | 1 | | 3 | 小米 | 小米科技有限公司 | 50 | are you ok | 1 | +----+------------+----------------------+---------+--------------------------------+--------+
|
参数文档druid.properties
内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| # 数据库驱动 driverClassName=com.mysql.cj.jdbc.Driver # 数据库连接 url=jdbc:mysql:///itcast?useSSL=false&useServerPrepStmts=true # 数据库用户名 username=root # 数据库密码 password=123456 #初始化连接数量 initialSize=5 #最大连接数 maxActive=10 #获取连接最大等待时间 maxWait=3000
|
查询所有数据,代码如下:
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
| @Test public void selectAll() throws Exception {
Properties prop = new Properties();
prop.load(new FileInputStream("src/main/java/druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
Connection conn = dataSource.getConnection();
String sql = "select * from tb_brand"; PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
List<Brand> brands = new ArrayList<>(); while(rs.next()){ int id = rs.getInt("id"); String brandName = rs.getString("brand_name"); String companyName = rs.getString("company_name"); int ordered = rs.getInt("ordered"); String description = rs.getString("description"); int status = rs.getInt("status");
Brand brand = new Brand(id, brandName, companyName, ordered,description, status); brands.add(brand); } System.out.println(brands); rs.close(); pstmt.close(); conn.close(); }
|
案例2 - 增删改
增加代码示例如下:
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
|
@Test public void selectAll() throws Exception {
Properties prop = new Properties();
prop.load(new FileInputStream("src/main/java/druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
Connection conn = dataSource.getConnection();
String brandName = "香飘飘"; String companyName = "香飘飘"; int ordered = 1; String description = "hello"; int status = 1;
String sql = "insert into tb_brand(brand_name, company_name,ordered,description,status) values(?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,brandName); pstmt.setString(2,companyName); pstmt.setInt(3,ordered); pstmt.setString(4,description); pstmt.setInt(5,status);
int i = pstmt.executeUpdate(); System.out.println(i > 0); pstmt.close(); conn.close(); }
|