2021年8月30日
咱们现在写代码,得有main主函数才能运行。
如果没有main主函数能运行代码吗?
能的
咱们使用的是一个注解的写法
@Test 下面修饰的是一个自定义的方法
需要导包 alt+enter Junit4这个jar包
package com.qfedu.a_test;
import org.junit.Test;
public class Test1 {
//@Test 是一个注解的写法
//@Override 是修饰一个方法的,这个方法是严格重写的方法
1.重新封装JdbcUtil
1.在src下面新建一文件,这个文件叫db.properties,等一会儿,咱们这个文件需要在
JdbcUti这个类下面需要读取这个文件里面的内容
package com.qfedu.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 1.完成驱动的自动加载
* 2.完成必要的数据处理 url user password
* 3.完成connection这个方法
* 4.完成统一的close方法
*/
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driver = null;
//使用静态代码块进行数据的加载和驱动的加载
static {
//需要去读取properties这个文件里面的内容
//1.需要创建一个properties对象,这个对象的功能就是读取properties这文件的
Properties properties = new Properties();
//2.使用load方法,加载src下面的db.properties这个文件
try {
//已经将咱们的db.properties文件里面的额内容已经加载到了properties对象中了
properties.load(new FileInputStream("./src/db.properties"));
//3.从properties这个对象获取值 4个值
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//简化getConnection方法的写法
//简化getConnection方法的写法
//封装一个静态的方法,获取connetion对象
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//现在封装的时候,我不知道需要关闭哪个资源
//有的需要关闭一个,有的需要关闭两个,有的需要关闭三个
//关闭一个资源 connection
public static void close(Connection connection) {
close(connection, null, null);
}
//关闭两个资源 connection statement
public static void close(Connection connection, Statement statement) {
close(connection, statement, null);
}
//关闭三个资源的 connection statement resultSet
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
if (connection != null) {
try {
connection.close();
} catch (