//这个类是JDBC连接数据库的工具类
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
@SuppressWarnings(“all”)
public class JDBCUtils {
private static final String DRIVER_CLASSNAME;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
DRIVER_CLASSNAME=properties.getProperty("driverClassName");
URL=properties.getProperty("url");
USERNAME=properties.getProperty("username");
PASSWORD=properties.getProperty("password");
}
/*
* 注册驱动的方法
* */
public static void loadDriver(){
try {
Class.forName(DRIVER_CLASSNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获得连接的方法
* */
public static Connection getConnection(){
Connection conn = null;
try {
//将驱动一并注册
loadDriver();
//获得连接
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/*
* 释放资源的方法
* */
public static void release(Statement sta,Connection conn){
if (sta != null){
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
sta = null;
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
conn = null;
}
public static void release(ResultSet rs,Statement sta,Connection conn){
//资源释放
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(sta,conn);
}
}
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day02
username=root
password=123123
//下边是测试类
public class Jdbc_test04 {
public static void main(String[] args) {
JDBCUtils jdbcUtils = new JDBCUtils();
}
}
当我实例化JDBCUtils工具类后发现,用“.”的方式不提示我们所写的静态方法。
这是因为idea这个软件帮我们优化代码,虽然用“.”的方式不提示我们所写的静态方法,但是当你把静态方法名写完之后它还是可以调用的,idea不建议你这么做,是因为你每new一次,就会占用一块内存。所以通过工具类名直接调用既方便又节省内存空间。

被折叠的 条评论
为什么被折叠?



