手动建立数据库连接的BaseDAO

时间:2023-02-01 17:24:13
package com.chinasoft.julong.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class BaseDAO {
private Connection conn;
private ResultSet rst;
private PreparedStatement pst; String className="oracle.jdbc.OracleDriver";
String useName="oracle";
String password="oracle";
String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; //加载数据库驱动程序
public BaseDAO(){
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//建立数据库连接
public void getConnection(){
try {
conn=DriverManager.getConnection(url,useName,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //不带参数的有查询结果集的函数(查询)
public ResultSet ExecuteQuery(String sql){
return ExecuteQuery(sql,new Object[]{});
} //带参数的有查询结果集的函数(查询)
public ResultSet ExecuteQuery(String sql,Object[] arry){
getConnection();
try {
pst=conn.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<arry.length;i++){
try {
pst.setObject(i+1, arry[i]);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
rst=pst.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
} //不带参数的更新函数(增加,修改,删除)
public int ExecuteUpdate(String sql){
return ExecuteUpdate(sql,new Object[]{});
}
//带参数的更新函数(增加,修改,删除)
public int ExecuteUpdate(String sql,Object[] arry){
getConnection();
int result=0;
try {
pst=conn.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<arry.length;i++){
try {
pst.setObject(i+1, arry[i]);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
result=pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Closed();
return result;
} //关闭数据库操作对象
public void Closed(){
try {
if(rst!=null&&!rst.isClosed()){
rst.close();
}
if(!pst.isClosed()){
pst.close();
}
if(!conn.isClosed()){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }