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();
}
}
}
}