packagecom.jdec.util_v3;importjava.io.IOException;importjava.io.InputStream;importjava.net.URL;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Properties;public classjdbcUtil {private staticString user;public staticString password;public staticString className;public staticString url;
Connection con=null;
PreparedStatement pstm=null;
ResultSet rs=null;static{//1.加載properties文件獲取inputStream
/*1.1 方式1.使用類加載ClassLoader加載src的資源(固定寫法)
* 獲得ClassLoader固定寫法:當前類.class.getClassLoader();*/InputStream is= jdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");//加載當前類同包下的資源,如果需要從src開始必須填寫/
InputStream is2=jdbcUtil.class.getResourceAsStream("jdbc2.properties");//加載src下的資源
InputStream is3=jdbcUtil.class.getResourceAsStream("/jdbc.properties");//使用Properties處理流//使用load() 方法加載指定的流
Properties props=newProperties();try{
props.load(is);//使用getProperty(key),獲取需要的值
className=props.getProperty("jdbc.className");
url=props.getProperty("jdbc.url");
user=props.getProperty("jdbc.user");
password=props.getProperty("jdbc.password");
}catch(IOException e) {
e.printStackTrace();
}
}publicjdbcUtil() {try{
Class.forName(className);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
}publicConnection getConnection() {try{
con=(Connection) DriverManager.getConnection(url, user, password);
}catch(SQLException e) {
con=null;
e.printStackTrace();
}returncon;
}publicResultSet excuteQuery(String sql, Object[] obj) {if (sql!=null){
con=getConnection();if(con!=null){try{
pstm=(PreparedStatement) con.prepareStatement(sql);if (obj!=null) {for(int i=0;i
pstm.setObject(i+1,obj[i]);
}
}
rs=pstm.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
}
}returnrs;
}public intexcuteUpdate(String sql, Object[] obj) {//TODO Auto-generated method stub
int flag=-1;if(sql!=null && obj!=null){
con=getConnection();if (con!=null) {try{
pstm=(PreparedStatement) con.prepareStatement(sql);for(int i=0;i
pstm.setObject(i+1, obj[i]);
}
flag=pstm.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
}
}returnflag;
}publicResultSet queryAll(String sql) {
con=getConnection();if(con!=null){try{
pstm=(PreparedStatement) con.prepareStatement(sql);
rs=pstm.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
}returnrs;
}public voidcloseAll() {//TODO Auto-generated method stub
if (rs!=null) {try{
rs.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}if (pstm!=null) {try{
pstm.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}if (con!=null) {try{
con.close();
}catch(SQLException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}