1.工具类的封装
问题: 每次进行CRUD操作,都要写一套JDBC,很繁琐
解决方案:将重复的操作,抽取到工具类中封装
1.加载驱动只需要一次---放到静态代码块
问题2: 直接在工具类中将数据库驱动,数据库名,用户名,密码写死了,不方便后续变更---硬编码
解决方案:需要变为软编码形式,使程序更灵活,维护性更强
1.1DBUtils
配置文件的抽取--db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mydb
username=root
password=123
public class DBUtils {
private static Properties p = new Properties();
//静态代码块:只加载一次
static{
//反射对象调用getResourceAsStream
//从src目录下获取到db.properties的资源
try {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
p.load(is);
Class.forName(p.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(AutoCloseable...cs){
for(AutoCloseable c : cs){
if(c!=null){
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
1.2LoginTest
public class LoginTest {
public static v