JDBC接口👻复习
JDBC概述
在开发中我们使用的是java语言,那么势必要通过java语言操作数据库中的数据。这就是接下来要学习的JDBC。
JDBC概念
JDBC 就是使用Java语言操作关系型数据库的一套API
全称:( Java DataBase Connectivity ) Java 数据库连接
我们开发的同一套Java代码是无法操作不同的关系型数据库,因为每一个关系型数据库的底层实现细节都不一样。如果这样,问题就很大了,在公司中可以在开发阶段使用的是MySQL数据库,而上线时公司最终选用oracle数据库,我们就需要对代码进行大批量修改,这显然并不是我们想看到的。我们要做到的是同一套Java代码操作不同的关系型数据库,而此时sun公司就指定了一套标准接口(JDBC),JDBC中定义了所有操作关系型数据库的规则。众所周知接口是无法直接使用的,我们需要使用接口的实现类,而这套实现类(称之为:驱动)就由各自的数据库厂商给出。
JDBC本质
- 官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口
- 各个数据库厂商去实现这套接口,提供数据库驱动jar包
- 我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类
JDBC好处
- 各数据库厂商使用相同的接口,Java代码不需要针对不同数据库分别开发
- 可随时替换底层数据库,访问数据库的Java代码基本不变
以后编写操作数据库的代码只需要面向JDBC(接口),操作哪儿个关系型数据库就需要导入该数据库的驱动包,如需要操作MySQL数据库,就需要再项目中导入MySQL数据库的驱动包。如下图就是MySQL驱动包
JDBC快速入门
先来看看通过Java操作数据库的流程
第一步:编写Java代码
第二步:Java代码将SQL发送到MySQL服务端
第三步:MySQL服务端接收到SQL语句并执行该SQL语句
第四步:将SQL语句执行的结果返回给Java代码
编写代码步骤
- 创建工程,导入驱动jar包 当时还没有学习Maven
单独连接
package A2_JDBC_API详解.B1_DriverManager;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement;
public class TestDriverManager {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql:///testsql?useSSL=false"; String user = "root"; String password = "ganga"; Connection conn = DriverManager.getConnection(url, user, password);
String sql = "update student set math = 99 where id = 8";
Statement stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(count);
stmt.close(); conn.close();
} }
|
事务提交&回滚
package A2_JDBC_API详解.B2_Connection;
import com.mysql.jdbc.exceptions.MySQLDataException;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Scanner;
public class TestConnection {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql:///testsql?useSSL=false"; String user = "root"; String password = "ganga"; Connection conn = DriverManager.getConnection(url, user, password);
String sql1 = "update student set math = 99 where id = 8"; String sql2 = "update student set math = 101 where id = 7";
Statement stmt = conn.createStatement();
try {
conn.setAutoCommit(false);
int count1 = stmt.executeUpdate(sql1); System.out.println(count1);
int count2 = stmt.executeUpdate(sql2); System.out.println(count2);
conn.commit();
}catch(Exception e){
conn.rollback(); e.printStackTrace(); }
stmt.close(); conn.close();
}
}
|
查询结果
package A2_JDBC_API详解.B4_ResultSet;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Scanner;
public class TestResultSet {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///ling?useSSL=false"; String user = "root"; String password = sc.next(); Connection conn = DriverManager.getConnection(url,user,password);
Statement stat = conn.createStatement();
String sql = "select * from stu";
ResultSet rs = stat.executeQuery(sql);
System.out.println("==========================");
while (rs.next()){ int id = rs.getInt("id"); String name = rs.getString(2); double score = rs.getDouble(3);
System.out.println(id); System.out.println(name); System.out.println(score); System.out.println("======================="); }
rs.close(); stat.close(); conn.close();
}
}
|
SQL注入 & 防SQL注入
package A2_JDBC_API详解.B5_PreparedStatement;
import java.sql.*; import java.util.Scanner;
public class TestSQL_Injection {
public static void main(String[] args) throws Exception {
new TestSQL_Injection().TestLogin_Injection();
}
public void TestLogin_Injection() throws Exception {
System.out.println("SQL注入演示使用: ' or '1' = '1 登录成功!"); Scanner sc = new Scanner(System.in);
System.out.print("请入账户:"); String user = sc.nextLine(); System.out.print("请输入密码:"); String password = sc.nextLine();
Connection conn = DriverManager.getConnection("jdbc:mysql:///ling?useSSL=false", "root", "ganga"); Statement statement = conn.createStatement();
String sql = "select * from user_password where user = '" + user + "' and password = '" + password + "'"; ResultSet rs = statement.executeQuery(sql);
if (rs.next()) { System.out.println("登录成功!"); } else { System.out.println("登录失败!"); }
rs.close(); statement.close(); conn.close();
}
public void TestLogin() throws Exception { System.out.println("防止SQL注入演示使用: ' or '1' = '1 登录失败!"); Scanner sc = new Scanner(System.in); System.out.print("请入账户:"); String user = sc.nextLine(); System.out.print("请输入密码:"); String password = sc.nextLine();
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///ling?useSSL=false", "root", "ganga");
String sql = "select * from user_password where user = ? and password = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,user); ps.setString(2,password);
ResultSet rs = ps.executeQuery(); if (rs.next()) { System.out.println("登录成功!"); } else { System.out.println("登录失败!"); }
rs.close(); ps.close(); conn.close();
}
public void TestPrepared_other(){
} }
|
连接池 Druid 德鲁伊连接池
配置文件
通过Druid获取Connection连接对象
package A3_JDBC_数据库连接池.德鲁伊;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.util.Properties;
public class TestDruid {
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("user.dir"));
Properties prop = new Properties(); prop.load(new FileInputStream("D:\\源代码\\A2_JavaWeb学习\\B2_JDBC接口学习\\src\\A3_JDBC_数据库连接池\\德鲁伊\\配置文件\\druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
Connection conn = dataSource.getConnection();
System.out.println(conn);
}
}
|
案例
查询
package A3_JDBC_数据库连接池.德鲁伊.案例_增删改查.查询;
import A3_JDBC_数据库连接池.德鲁伊.案例_增删改查.Brand; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.jupiter.api.Test;
import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Properties;
public class TestQuery_JDBC {
@Test public void query() throws Exception{
Properties prop = new Properties(); prop.load(new FileInputStream("D:\\源代码\\A2_JavaWeb学习\\B2_JDBC接口学习\\src\\A3_JDBC_数据库连接池\\德鲁伊\\配置文件\\druid.properties")); DataSource ds = DruidDataSourceFactory.createDataSource(prop); Connection conn = ds.getConnection();
String querySQL = "select * from tb_brand";
PreparedStatement ps = conn.prepareStatement(querySQL);
ResultSet rs = ps.executeQuery();
List<Brand> list = new ArrayList<>(); Brand brand = null;
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 = new Brand(); brand.setId(id); brand.setBrandName(brandName); brand.setCompanyName(companyName); brand.setOrdered(ordered); brand.setDescription(description); brand.setStatus(status);
list.add(brand);
}
rs.close(); ps.close(); conn.close();
for (Brand br: list) { System.out.println(br); }
}
}
|
修改
package A3_JDBC_数据库连接池.德鲁伊.案例_增删改查.修改;
import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.jupiter.api.Test;
import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties;
public class TestUpdate_JDBC {
@Test public void updateTest() throws Exception{
Properties prop = new Properties(); prop.load(new FileInputStream("D:\\源代码\\A2_JavaWeb学习\\B2_JDBC接口学习\\src\\A3_JDBC_数据库连接池\\德鲁伊\\配置文件\\druid.properties")); DataSource ds = DruidDataSourceFactory.createDataSource(prop); Connection conn = ds.getConnection();
String updateSql = "update tb_brand set \n" + " brand_name = ?,\n" + " company_name = ?,\n" + " ordered = ?,\n" + " description = ?,\n" + " status = ?\n" + "where id = ?;";
PreparedStatement ps = conn.prepareStatement(updateSql);
ps.setString(1,"英雄联盟"); ps.setString(2,"拳头游戏"); ps.setInt(3,1); ps.setString(4,"赏金yyds"); ps.setInt(5,1); ps.setInt(6,4);
int num = ps.executeUpdate();
if (num == 1){ System.out.println(true); }else{ System.out.println(false); }
ps.close(); conn.close();
}
}
|
添加
package A3_JDBC_数据库连接池.德鲁伊.案例_增删改查.添加;
import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.jupiter.api.Test;
import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties;
public class TestAdd_JDBC {
@Test public void addTest() throws Exception{
Properties prop = new Properties(); prop.load(new FileInputStream("D:\\源代码\\A2_JavaWeb学习\\B2_JDBC接口学习\\src\\A3_JDBC_数据库连接池\\德鲁伊\\配置文件\\druid.properties")); DataSource ds = DruidDataSourceFactory.createDataSource(prop); Connection conn = ds.getConnection();
String addSql = "insert into tb_brand (brand_name,company_name,ordered,description,status) values (?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(addSql);
ps.setString(1,"LOL"); ps.setString(2,"Riot Games"); ps.setInt(3,2); ps.setString(4, "good LOL"); ps.setInt(5,1);
int i = ps.executeUpdate();
if (i == 1){ System.out.println("数据添加成功"); }else{ System.out.println("数据添加失败"); }
ps.close(); conn.close();
}
}
|
删除
package A3_JDBC_数据库连接池.德鲁伊.案例_增删改查.删除;
import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.jupiter.api.Test;
import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties;
public class TestDelete_JDBC {
@Test public void deleteTest() throws Exception{
Properties prop = new Properties(); prop.load(new FileInputStream("D:\\源代码\\A2_JavaWeb学习\\B2_JDBC接口学习\\src\\A3_JDBC_数据库连接池\\德鲁伊\\配置文件\\druid.properties")); DataSource ds = DruidDataSourceFactory.createDataSource(prop); Connection conn = ds.getConnection();
String deleteSql = "delete from tb_brand where id = ?";
PreparedStatement ps = conn.prepareStatement(deleteSql);
ps.setInt(1,4);
int num = ps.executeUpdate();
if (num == 1){ System.out.println(true); }else{ System.out.println(false); }
ps.close(); conn.close();
}
}
|
单词
单词 |
解释 |
DriverManager |
驱动管理 |
Connection |
连接 |
Statement |
陈述;说明 |
execute |
处决 |
Update |
修改 |
Query |
查询 |
ResultSet |
结果集 |
PreparedStement |
预备 & 说明 [类] |
prepareStement |
准备 & 说明 [方法] |
setAutoCommit |
设置自动提交 |
commit |
提交 |
rollback |
回滚 |
|
|
Druid |
德鲁伊 |
Properties |
属性 |
load |
装载 |
DataSource |
数据源 |
DruidDataSourceFactory |
德鲁伊数据源工厂 |
|
|
|
|