DBUtil以及对static的理解
名为dbInfo的properties文件的配置:
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/my
username = root
password = 1993zl
DBUtil类:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class DBUtil {
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
//静态变量被所有的对象所共享,在内存中只有一个副本
private static String driver;
private static String url;
private static String username;
private static String password;
//用静态块里面的代码只会在类加在的时候执行一次,不会造成资源浪费
static{
//加载properties文件数据
ResourceBundle rb = ResourceBundle.getBundle("dbInfo");
driver = rb.getString("driver");
url = rb.getString("url");
username = rb.getString("username");
password = rb.getString("password");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//静态方法不需要new对象,直接通过类名来调用
public static Connection getConnection() throws SQLException{
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps = null;
}
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
}
测试类Test
public class Test(){
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn = DBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement("select ENAME from emp where sal=?");
ps.setInt(1, 1250);
//ps.setInt(1, 10);
ResultSet rs =ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ENAME"));
}
DBUtil.closeAll(conn, ps, rs);
}
输处结果:
}