JDBCDemo
java
package study;
import com.easy.web.pojo.Student;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBCDemo {
@Test
public void test1(){
try {
//1、加载驱动Class.forName(""); (不需要背,能看懂就行)
Class.forName("com.mysql.cj.jdbc.Driver");
//2、获得连接对象Connection (不需要背,能看懂就行)(jdbc:mysql(协议)://localhost(找到本机):3306(访问mysql)/study?(数据库的名字)后面是一些属性设置)
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234");
//3、写sql语句
String sql = "SELECT id,name,age,gender FROM student";
//4、创建Statement(一艘船) (用连接(connection)创建)
Statement statement = connection.createStatement(); //(后面用PreparedStatement代替Statement)
//5、执行sql语句 (statement执行)
// (1) 更新类(更改了表里面数据):delete/update/insert executeUpdate()
// 返回值:int,表示你影响的行数
// (2)查询(没有改变表里面数据): select executeQuery()
// 返回值:结果集ResultSet
ResultSet resultSet = statement.executeQuery(sql);
//(创建一个列表保存Student)
List<Student> list = new ArrayList<>();
//判断下一个还有没有,有返回true,没有返回false
while (resultSet.next()){
//while循环每遍历一次,就把这一行的字段值全拿出来,封装成一个Student
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
//封装Student
Student student = new Student(id,name,age,gender);
//将封装完成的Student存入list集合中
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally{
//6、关闭连接
}
}
@Test
//用PreparedStatement代替Statement,效率更高且可以防止sql注入,Statement不能防止sql注入
//sql注入:不规范输入影响了代码结构,使代码逻辑出错,执行非预期操作
public void test2() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234");
String sql = "SELECT id,name,age,gender FROM student";
//4、创建PreparedStatement(一艘船) (用连接(connection)创建)
PreparedStatement preparedStatement = connection.prepareStatement(sql); //可以直接用sql进行预编译,执行的时候就不需要传sql,效率更高
ResultSet resultSet = preparedStatement.executeQuery(); //不用传入sql作为参数
List<Student> list = new ArrayList<>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
Student student = new Student(id, name, age, gender);
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
//6、关闭连接
}
}
@Test
//关闭连接
public void test3() {
//提前声明扩大作用域
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//上面已经声明过了,不需要再声明
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234");
String sql = "SELECT id,name,age,gender FROM student";
//与connection同理
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
List<Student> list = new ArrayList<>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
Student student = new Student(id, name, age, gender);
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
//6、关闭连接
//需要关闭的有connection、preparedStatement、resultSet,
//但是在Test2的结构中,在finally这里拿不到这三个变量,所以需要将这三个变量声明在最前面
//后打开先关闭
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
@Test
//将重复的内容抽取为工具类
public void test4() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//利用工具类方法获取连接
connection = JDBCUtil.getConnection();
String sql = "SELECT id,name,age,gender FROM student";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
List<Student> list = new ArrayList<>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
Student student = new Student(id, name, age, gender);
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
}
//ClassNotFoundException在JDBCUtil静态代码块中已被捕获,所以不需要在这里再捕获了
catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil.close(connection, preparedStatement, resultSet);
}
}
@Test
public void testInsert(){
Connection connection = null;
PreparedStatement preparedStatement = null;
//不是查询类,没有结果集
try {
connection = JDBCUtil2.getConnection();
String sql = "INSERT INTO student(id,name,age,gender) VALUES(?,?,?,?)";
//一个一个填补括号中的"?"
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,10);
preparedStatement.setString(2,"张三11");
preparedStatement.setInt(3,23);
preparedStatement.setString(4,"男");
//打印出来,显示在执行什么语句(非必须)
System.out.println(preparedStatement);
//返回影响行数
int count = preparedStatement.executeUpdate();
System.out.println("count: " + count);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil2.close(connection,preparedStatement,null);
}
}
@Test
public void testDelete(){
Connection connection = null;
PreparedStatement preparedStatement = null;
//不是查询类,没有结果集
try {
connection = JDBCUtil2.getConnection();
String sql = "DELETE FROM student WHERE id=?";
//一个一个填补括号中的"?"
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,10);
//打印出来,显示在执行什么语句(非必须)
System.out.println(preparedStatement);
//返回影响行数
int count = preparedStatement.executeUpdate();
System.out.println("count: " + count);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil2.close(connection,preparedStatement,null);
}
}
@Test
public void testUpdate(){
Connection connection = null;
PreparedStatement preparedStatement = null;
//不是查询类,没有结果集
try {
connection = JDBCUtil2.getConnection();
String sql = "UPDATE student SET name=?,age=?,gender=? WHERE id=?";
//一个一个填补括号中的"?"
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"李四11");
preparedStatement.setInt(2,24);
preparedStatement.setString(3,"男");
preparedStatement.setInt(4,9);
//打印出来,显示在执行什么语句(非必须)
System.out.println(preparedStatement);
//返回影响行数
int count = preparedStatement.executeUpdate();
System.out.println("count: " + count);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil2.close(connection,preparedStatement,null);
}
}
//模糊查找
@Test
public void testLike() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtil.getConnection();
String sql = "SELECT id,name,age,gender FROM student WHERE name LIKE ?";
preparedStatement = connection.prepareStatement(sql);
//填补"?"
preparedStatement.setString(1,"%张%");
System.out.println(preparedStatement);
resultSet = preparedStatement.executeQuery();
List<Student> list = new ArrayList<>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
Student student = new Student(id, name, age, gender);
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
}
catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil.close(connection, preparedStatement, resultSet);
}
}
}
JDBCUtil
java
package study;
import java.sql.*;
//将重复代码块封装为Util工具类
public class JDBCUtil {
//因为驱动只需要加载一次,如果放在下面的方法当中,每次调用方法都会加载驱动,
//利用静态代码块保证驱动只加载一次
static {
//1、加载驱动Class.forName(""); (不需要背,能看懂就行)
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//需要有一个方法获取连接
//返回值类型为Connection
public static Connection getConnection() throws SQLException { //(抛出getConnection的异常,调用时catch一下即可,在这里直接try catch也可以)
//2、获得连接对象Connection (不需要背,能看懂就行)(jdbc:mysql(协议)://localhost(找到本机):3306(访问mysql)/study?(数据库的名字)后面是一些属性设置)
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234");
return connection;
}
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
JDBCUtil2
java
package study;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
//当把driver、url、username、password放在代码中时,因为都是写死的,不容易进行修改
//所以也将这些东西单独拿出来作为Util的一部分,代码中直接获取即可
public class JDBCUtil2 {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
//加载文件(与加载驱动分开)
try {
//1.通过当前类获取类加载器
ClassLoader classLoader = JDBCUtil2.class.getClassLoader();
//2.通过类加载器获取输入流
//参数传入properties文件名(放在resources文件夹中)
InputStream inputStream = classLoader.getResourceAsStream("db.properties");
//3.创建一个properties对象加载输入流
Properties properties = new Properties();
properties.load(inputStream);
//4.根据key获取配置文件中对应的value值
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (IOException e) {
throw new RuntimeException(e);
}
//加载驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException { //(抛出getConnection的异常,调用时catch一下即可,在这里直接try catch也可以)
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
Student类
java
package com.easy.web.pojo;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
private String gender;
public Student() {
}
public Student(Integer id, String name, Integer age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}