将连接数据库的JDBC提成BaseDao

package com.shangke;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
* 用来操纵数据库的类
*/
public class BeseDao {
private static String url ="";
private static String user ="";
private static String password ="";
private static String driver ="";
private Connection conn = null;//数据库连接对象 connection
PreparedStatement ps =null;//执行Sql statement对象
ResultSet rs=null;//结果集
//因为只需加载一次所以就是用static代码块就可以了
static{
Properties pro=new Properties();
//获取读src下的输入流
InputStream resourceStream = BeseDao.class.getClassLoader().getResourceAsStream("JDBC.properties");
try {
//加载输入流
pro.load(resourceStream );
//读取文件的key值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//加载驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//关闭流
if(resourceStream!=null){
try {
resourceStream .close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

//获取数据库连接
public boolean getConnection(){
try {
//将连接对象赋值
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;

}

//数据库增删改
public int updataSQL(String sql,Object[]... obj) {
int indenx =-1;
//先获取到连接对象
if(this.getConnection()){
try {
//使用连接对象 获取statement对象
ps = conn.prepareStatement(sql);
//填充占位符
for(int i=0;i<obj.length;i++){
ps.setObject(i+1,obj[i]);
}
indenx = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
return indenx;
}
//数据库查询
public ResultSet querySQL(String sql, Object[]... obj) {
if(this.getConnection()){
try {
ps=conn.prepareStatement(sql);
//填充占位符
for(int i=0;i<obj.length;i++){
ps.setObject(i+1,obj[i]);
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}

return rs;
}
//释放资源
public void close(){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/xinjingsiyuan/p/10506959.html