代码示例:import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.com.sun.org
.apache.xml.internal.security.Init;
public class BaseDao {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/epet";
private static String user = "root";
private static String password = "root";
Connection con = null;
static {
Init();
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接并捕获异常
* @return
*/
public Connection getConnection() {
try {
if(con==null){
con = DriverManager.getConnection(
url,user,password);
}
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
private static void Init() {
Properties params=new Properties();
String config="database.properties";
InputStream is=BaseDao.class.getClassLoader().getResourceAsStream(config);
try {
params.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver=params.getProperty("driver");
url=params.getProperty("url");
user=params.getProperty("user");
password=params.getProperty("password");
}
/**
* 关闭数据库连接
*/
public void closeAll(ResultSet rs,Statement st,Connection con){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e1){
e1.printStackTrace();
}
try {
if(st!=null){
st.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
if(con!=null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 增删改操作
* @param sql
* @param param
* @return
*/
public int exceuteUpdate(String sql,Object[] param){
PreparedStatement ps=null;
int result=0;
con=getConnection();
try {
ps=con.prepareStatement(sql);
if(param!=null){
for (int i = 0; i
ps.setObject(i+1,param[i]);
}
}
result=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll(null, ps, con);
}
return result;
}
}