JDBC
1.
public void test1() throws SQLException {
//获取Driver的实现类对象
Driver driver=new com.mysql.cj.jdbc.Driver();
//指明需要连接的数据库
String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
//将用户名密码封装在properites中
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","abc123");
//获取连接
Connection conn= driver.connect(url,info);
System.out.println(conn);
}
2.通过反射
public void test2() throws Exception {
//1.获取Driver实现类对象:使用反射
Class clazz= Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2.提供要连接的数据库
String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
//3.提供连接需要的用户名和密码
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","abc123");
//4.获取连接
Connection conn= driver.connect(url,info);
System.out.println(conn);
}
3.通过DriverManager 替换Driver
public void test3() throws SQLException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//方式三:使用DriverManager替换Driver
//获取三个连接的基本信息
String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
String user="root";
String password="abc123";
//新版本已经不需要注册驱动,注册驱动被封装在获取连接中
// Class<?> clazz = Class.forName("com.mysql.cj.jdbc.Driver");
// Driver driver= (Driver) clazz.getDeclaredConstructor().newInstance();
// //注册驱动
// DriverManager.registerDriver(driver);
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
4.对方式三的优化
public void test4() throws Exception {
//方式四:对方式三的优化
//1.获取三个连接的基本信息
String url="jdbc:mysql://localhost:3306/test?&serverTimezone=UTC";
String user="root";
String password="abc123";
//2.加载Driver
//新版本已经不需要注册驱动,注册驱动被封装在获取连接中
Class.forName("com.mysql.cj.jdbc.Driver");
// Driver driver= (Driver) clazz.getDeclaredConstructor().newInstance();
// //注册驱动
// DriverManager.registerDriver(driver);
//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
5.最终版
public void test5() throws Exception {
//方式五:最终版
//将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式获取连接
//1.读取配置文件中的4个基本信息
//通过类的加载器
InputStream is = ConnectTest.class.getClassLoader().getResourceAsStream("JDBC.properties");
Properties pro=new Properties();
pro.load(is);
String user = pro.getProperty("user");
String password=pro.getProperty("password");
String driver = pro.getProperty("driver");
String url = pro.getProperty("url");
//2.加载驱动
Class.forName(driver);
//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
二.PrepareStatement实现修改数据库
1.增删改 PrepareStatement.execute();
//向customers表中添加一条记录
2.查 PrepareStatement.executeQuery()
package PreparedStatement;
/**
* <h5>描述:</h5>
*/
import Bean.Customers;
import Utils.JDBCUtils;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.sql.*;
/**
* @Description 针对Customers表的查询操作
*/
public class CustomersForQuery {
