DriverManger (驱动管理类)作用:
- 注册驱动
- 获取数据库连接
Class.forName("com.mysql.jdbc.Driver");
查看 Driver 类的源码:
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
提示:
META-INF/services/java.sql.Driver
文件中的驱动类static Connection getConnection(String url,String user,String password)
jdbc:mysql://ip地址(域名):端口号/数据库名称?参数键值对1&参数键值对2......
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql:///数据库名称?参数键值对
useSSL=false
参数,禁用安全连接方式,解决警告提示 public static void main(String[] args) throws Exception {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
// 获取连接
Connection connection = DriverManager.getConnection(url, username, password);
String sql="update account set money=2000 where id=1";
Statement statement = connection.createStatement();
// 执行 SQL 语句
int i = statement.executeUpdate(sql);
// 处理结果
System.out.println(i);
statement.close();
connection.close();
}
Connection (数据库连接对象)作用:
- 获取执行 SQL 的对象
- 管理事务
Statement createStatement()
PreparedStatement preparedStatement(sql)
CallableStatament prepareCall(sql)
BEGING; / START TRANSACTION;
COMMIT;
ROLLBACK;
setAutoCommit(boolean autoCommit);
true 为自动提交事务;false 为手动提交事务,即为开启事务commit();
rollback();
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
String sql="update account set money=2000 where id=1";
Statement statement = connection.createStatement();
try {
// 开启事务
connection.setAutoCommit(false);
int i = statement.executeUpdate(sql);
System.out.println(i);
// 提交事务
connection.commit();
} catch (Exception e) {
// 回滚事务
connection.rollback();
e.printStackTrace();
}
statement.close();
connection.close();
}
Statement 作用:
执行 SQL 语句
int executeUpdate(sql)
:执行 DML,DDL 语句
ResultSet executeQuery(sql)
:执行 DQL 语句
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
String sql="update account set money=2000 where id=1";
Statement statement = connection.createStatement();
// 执行 DML 语句受影响的行数
int count = statement.executeUpdate(sql);
if (count>0){
System.out.println("修改成功!");
}else {
System.out.println("修改失败!");
}
statement.close();
connection.close();
}
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
String sql="create database test";
// String sql="drop database test"; 此条语句执行成功之后返回零
Statement statement = connection.createStatement();
// 执行 DDL 语句受影响的行数
int count = statement.executeUpdate(sql);
if (count>0){
System.out.println("修改成功!");
}else {
System.out.println("修改失败!");
}
// 所以执行 DDL 语句就不能使用这样的判断语句
statement.close();
connection.close();
}
ResultSet(结果集对象)作用
封装了 DQL 查询语句的结果
ResultSet statement.executeQuery(sql)
:执行 DQL 语句,返回 ResultSet 对象
获取查询结果:
boolean next()
:(1)将光标从当前位置向前移动一行。(2)判断当前行是否为有效行
xxx getXxx(参数)
:获取数据
int getInt(参数);
String getString(参数);
使用步骤:
next();
getXxx(参数);
// 循环判断游标是否是最后一行结尾
while(resultSet.next()){
// 获取数据
resultSet.getXxx(参数);
}
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
// 定义 SQL 语句
String sql="select * from account";
// 获取 statement 对象
Statement statement = connection.createStatement();
// 执行 SQL 语句
ResultSet resultSet = statement.executeQuery(sql);
// 处理结果,遍历 resultSet 中的所有数据
// 光标向下移动一行,并且判断当前行是否有数据
while (resultSet.next()){
// 获取数据 getXxx();
int id= resultSet.getInt(1);
String name= resultSet.getString(2);
double money= resultSet.getDouble(3);
// 或者如下写法:
// int id= resultSet.getInt("id");
// String name= resultSet.getString("name");
// double money= resultSet.getDouble("money");
System.out.println(id);
System.out.println(name);
System.out.println(money);
System.out.println("------");
}
// 关闭资源
resultSet.close();
statement.close();
connection.close();
}
查询 account 账户表数据,封装为 Account 对象中,并且存储到 ArrayList 集合中
public class Account {
private int id;
private String name;
private double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
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 double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
String sql="select * from account";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
// 创建集合
ArrayList<Account> list = new ArrayList<>();
while (resultSet.next()){
Account account = new Account();
int id= resultSet.getInt(1);
String name= resultSet.getString(2);
double money= resultSet.getDouble(3);
// 赋值
account.setId(id);
account.setName(name);
account.setMoney(money);
// 存入集合
list.add(account);
}
// 打印集合
System.out.println(list);
// 关闭资源
resultSet.close();
statement.close();
connection.close();
}
PreparedStatement 作用:
预编译 SQL 语句并执行:预防 SQL 注入问题
SQL 注入:SQL 注入是通过操作输入来修改事先定义好的 SQL 语句,用以达到执行代码对服务器进行攻击的方法
完成用户登录:
select * from user where username='张三' and password='123';
正常登录:
public void testLogin() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
// 接收用户输入 用户名和密码
String name="张三";
String pwd="123";
String sql="select * from user where username='"+name+"'and password='"+pwd+"'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()){
System.out.println("登陆成功!");
}else {
System.out.println("登陆失败!");
}
resultSet.close();
statement.close();
connection.close();
}
SQL 注入:
public void testInject() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
// 接收用户输入 用户名和密码
String name="李四";
String pwd="' or '1' = '1";
String sql="select * from user where username'"+name+"'and password='"+pwd+"'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()){
System.out.println("登陆成功!");
}else {
System.out.println("登陆失败!");
}
resultSet.close();
statement.close();
connection.close();
}
// SQL 语句中的参数值,使用 ? 占位符替代
String sql="select * from user where username=? and password=?";
// 通过 Connection 对象获取,并传入对应的 SQL 语句
PreparedStatement preparedStatement=connection.preparedStatement(sql);
setXxx(参数1,参数2)
:给 ? 赋值setInt(参数1,参数2)
executeUpdate();
executeQuery();
:不需要再传递 SQL public void testLogin() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
Connection connection = DriverManager.getConnection(url, username, password);
// 接收用户输入 用户名和密码
String name="李四";
String pwd="1234";
// 定义 SQL 语句
String sql="select * from user where username=? and password=?";
// 获取 prepareStatement 对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置 ? 的值
preparedStatement.setString(1,name);
preparedStatement.setString(2,pwd);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
System.out.println("登陆成功!");
}else {
System.out.println("登陆失败!");
}
resultSet.close();
preparedStatement.close();
connection.close();
}
useServerPrepStmts=true;
添加到 URL 之后(使用 &
字符)log-output=FILE
general-log=1
general_log_file="E:\MySQL\mysql.log"
slow-query-log=1
slow_query_log_file="E:\MySQL\mysql_slow.log"
long_query_time=2
Connection getConnection();
配置文件:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useServerPrepStmts=true&useSSL=false
username=root
password=root
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=1000
public static void main(String[] args) throws Exception {
// 加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("jdbc_01\\src\\druid.properties"));
// 获取连接对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// 获取数据库连接 Connection
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
// 定义成员变量
private static DataSource dataSource;
static {
try {
// 加载配置文件
Properties properties = new Properties();
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
// 获取 DataSource
dataSource= DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
// 获取连接池方法
public static DataSource getDataSource(){
return dataSource;
}
// 释放资源
public static void close(Statement statement, Connection connection){
close(null,statement,connection);
}
// 重写方法
public static void close(ResultSet resultSet,Statement statement,Connection connection){
if (resultSet!=null){
try {
resultSet.close();
}catch (SQLException e){
e.printStackTrace();
}
}
if (statement!=null){
try {
statement.close(); // 归还连接
}catch (SQLException e){
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
Spring 框架对 JDBC 的简单封装,提供了一个 JdbcTemplate 对象简化 JDBC 开发
JdbcTemplate template=new JdbcTemplate(dataSource);
update()
:执行 DML 语句,增、删、改语句queryForMap()
:查询结果将结果集封装为 Map 集合(注意:查询结果将结果封装为 Map 集合,将列名作为 key,将值作为 value ,将这条数据(记录)封装为一个 Map 集合)queryForList()
:查询结果将结果集封装为 List 集合(注意:将每一条记录封装为一个 Map 集合,再将 Map 集合装载到 List 集合中)query()
:查询结果,将结果封装为 JavaBean 对象(query 的参数:RowMapper,一般使用 BeanPropertyRowMapper 实现类,可以完成数据到 JavaBean 自动封装:new BeanPropertyRowMapper<泛型类型>(泛型类型.class)
)queryForObject()
:查询结果,将结果封装为对象(一般用于聚合函数的查询)pom.xml
<groupId>com.examplegroupId>
<artifactId>jdbc_testartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.3.6version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.32version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.6version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>5.3.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>5.3.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.3.6version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.12version>
dependency>
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiterartifactId>
<version>RELEASEversion>
<scope>compilescope>
dependency>
dependencies>
依赖上文中定义的工具类获取的数据源:
import com.example.utils.JDBCUtils; // 依赖于之前定义的工具类获取数据源
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTest01 {
public static void main(String[] args) {
// 创建 JdbcTemplate 对象
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
// 调用方法
String sql="update account set money=5000 where id=?";
int count = template.update(sql, 3);
System.out.println(count);
}
}
需求:(使用创建的数据库中的一张表)
public class JdbcTest02 {
// 获取 JdbcTemplate 对象
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
// 修改 id 为 1 的数据的 money 为10000
@Test
public void test01(){
String sql="update account set money=10000 where id=1";
int count = jdbcTemplate.update(sql);
System.out.println(count);
}
// 添加一条记录
@Test
public void test02(){
String sql="insert into account(id,name,money) values(?,?,?)";
int count = jdbcTemplate.update(sql, 4,"赵六", 500);
System.out.println(count);
}
// 删除刚才添加的记录
@Test
public void test03(){
String sql="delete from account where id=?";
int count = jdbcTemplate.update(sql, 4);
System.out.println(count);
}
}
// 查询 id 为1 的记录,将其封装为 Map 集合
@Test
public void test04() {
String sql = "select * from account where id=?";
Map<String, Object> map = jdbcTemplate.queryForMap(sql, 1);
System.out.println(map);
}
// 查询所有记录,将其封装为 List 集合
@Test
public void test05() {
String sql = "select * from account";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}
// 查询所有记录,将其封装为 Account 对象的 List 集合
@Test
public void test06_1() {
String sql = "select * from account";
List<Account> list = jdbcTemplate.query(sql, new RowMapper<Account>() {
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int money = resultSet.getInt("money");
account.setId(id);
account.setName(name);
account.setMoney(money);
return account;
}
});
for (Account account : list) {
System.out.println(account);
}
}
@Test
public void test06_02() {
String sql = "select * from account";
// 使用 Spring 提供好的封装类
List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
for (Account account : list) {
System.out.println(account);
}
}
// 查询总记录数
@Test
public void test07() {
String sql = "select count(id) from account";
Long total = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(total);
}
create table brand(
id int primary key auto_increment,
brand_name varchar(20),
company_name varchar(20),
ordered int,
description varchar(100),
status int
);
insert into brand (brand_name, company_name, ordered, description, status)
VALUES ('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0),
('华为','华为技术有限公司',100,'华为文化',1),
('小米','小米科技有限公司',50,'雷军-雷布斯',1);
select * from brand;
public class Brand {
// 在实体类中,基本数据类型建议使用对应的包装类
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
private Integer status;
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
步骤:
- 获取 Connection
- 定义 SQL 语句
- 获取 PreparedStatement 对象
- 设置参数
- 执行 SQL 语句
- 处理结果
- 释放资源
@Test
public void testSelectAll() throws Exception {
// 加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("jdbc_01\\src\\druid.properties"));
// 获取连接对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// 获取数据库连接 Connection
Connection connection = dataSource.getConnection();
// 定义 SQL 语句
String sql="select * from brand;";
// 获取 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 执行 SQL 语句
ResultSet resultSet = preparedStatement.executeQuery();
// 处理结果 封装对象进入集合
List<Brand> brands = new ArrayList<>();
Brand brand=null;
while (resultSet.next()){
// 获取数据
int id = resultSet.getInt("id");
String brandName = resultSet.getString("brand_name");
String companyName = resultSet.getString("company_name");
int ordered = resultSet.getInt("ordered");
String description = resultSet.getString("description");
int status = resultSet.getInt("status");
// 封装 Brand 对象
brand=new Brand();
brand.setId(id);
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(ordered);
brand.setDescription(description);
brand.setStatus(status);
// 装载集合
brands.add(brand);
}
System.out.println(brands);
// 关闭资源
resultSet.close();
preparedStatement.close();
connection.close();
}
@Test
public void testAdd() throws Exception {
// 接收页面提交的参数
String brandName="苹果";
String companyName="苹果公司";
int ordered=1;
String description="iPhone/Mas";
int status=1;
// 加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("jdbc_01\\src\\druid.properties"));
// 获取连接对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// 获取数据库连接 Connection
Connection connection = dataSource.getConnection();
// 定义 SQL 语句
String sql="insert into brand(brand_name,company_name,ordered,description,status) values (?,?,?,?,?)";
// 获取 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数
preparedStatement.setString(1,brandName);
preparedStatement.setString(2,companyName);
preparedStatement.setInt(3,ordered);
preparedStatement.setString(4,description);
preparedStatement.setInt(5,status);
// 执行 SQL 语句
int count = preparedStatement.executeUpdate();
// 处理结果
System.out.println(count>0);
// 关闭资源
preparedStatement.close();
connection.close();
}
@Test
public void testUpdate() throws Exception {
// 接收页面提交的参数
String brandName="苹果";
String companyName="苹果公司";
int ordered=1000;
String description="iPhone/Mas";
int status=1;
int id=4;
// 加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("jdbc_01\\src\\druid.properties"));
// 获取连接对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// 获取数据库连接 Connection
Connection connection = dataSource.getConnection();
// 定义 SQL 语句
String sql="update brand set brand_name=?,company_name=?,ordered=?,description=?,status=? where id=?";
// 获取 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数
preparedStatement.setString(1,brandName);
preparedStatement.setString(2,companyName);
preparedStatement.setInt(3,ordered);
preparedStatement.setString(4,description);
preparedStatement.setInt(5,status);
preparedStatement.setInt(6,id);
// 执行 SQL 语句
int count = preparedStatement.executeUpdate();
// 处理结果
System.out.println(count>0);
// 关闭资源
preparedStatement.close();
connection.close();
}
@Test
public void testDeleteById() throws Exception {
// 接收页面提交的参数
int id=4;
// 加载配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("jdbc_01\\src\\druid.properties"));
// 获取连接对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
// 获取数据库连接 Connection
Connection connection = dataSource.getConnection();
// 定义 SQL 语句
String sql="delete from brand where id=?;";
// 获取 preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数
preparedStatement.setInt(1,id);
// 执行 SQL 语句
int count = preparedStatement.executeUpdate();
// 处理结果
System.out.println(count>0);
// 关闭资源
preparedStatement.close();
connection.close();
}