对 JDBC 做一个轻量地封装,顺便复习,熟悉sql,io,util,lang.Reflect等包的使用,泛型的使用,待完善。。。
package com.yli.utils;
import java.sql.*;
import java.io.*;
import java.util.Properties;
public class DBConnection {
private static String driver=null,
url=null,
user=null,
password=null,
filename="src/jdbc.properties";
private static Properties pro=new Properties();
static {
try {
InputStream in = new BufferedInputStream(new FileInputStream(filename));
pro.load(in);
if (pro != null) {
driver = pro.getProperty("driver");
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static Connection getConn(){
Connection conn=null;
try{
Class.forName(driver);
conn=DriverManager.getConnection(url,user,password);
}
catch(SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(Connection conn,PreparedStatement preStmt,ResultSet rs){
if(conn!=null){
try{conn.close();}
catch(SQLException e){
e.printStackTrace();
}
finally{
conn=null;
}
}
if(preStmt!=null){
try{preStmt.close();}
catch(SQLException e){
e.printStackTrace();
}
finally{
preStmt=null;
}
}
if(rs!=null){
try{rs.close();}
catch(SQLException e){
e.printStackTrace();
}
finally{
rs=null;
}
}
}
public static void main(String [] args){
Connection conn=DBConnection.getConn();
if(conn!=null){
System.out.println("it‘s not null!");
}
}
}