import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
private final static String DRIVERNAME="oracle.jdbc.driver.OracleDriver";
private final static String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
private final static String UID="scott";
private final static String PWD="tiger";
protected Connection connection;
protected PreparedStatement ps;
protected ResultSet rs;
static{
try {
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败:"+e.getMessage());
System.out.println("加载驱动失败:"+URL);
}
}
public Connection getConnection(){
try {
connection=DriverManager.getConnection(URL,UID,PWD);
System.out.println(" 数据库连接成功");
} catch (SQLException e) {
System.out.println("建立连接失败:"+e.getMessage());
System.out.println("建立连接失败:"+URL);
}
return connection;
}
public int update(String sql,String args[]){
int i=-1;
Connection c=getConnection();
try {
ps=c.prepareStatement(sql);
if(null==args||0==args.length){
}else{
for(int j = 0;j< args.length;j++){
ps.setString(j+1, args[j]);
}
}
System.out.println("执行了");
i=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("执行语句失败:"+sql);
System.out.println("执行语句失败"+e.getMessage());
}finally{
closeAll(connection,ps,rs);
}
return i;
}
protected void closeAll(Connection connection,PreparedStatement ps,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean query(String sql, String[] args) {
Connection c=getConnection();
if(c==null){
return false;
}
try {
ps=c.prepareStatement(sql);
if(null==args||0==args.length){
}else{
for(int j = 0;j< args.length;j++){
ps.setString(j+1, args[j]);
}
}
rs=ps.executeQuery();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("执行语句失败:"+sql);
System.out.println("执行语句失败"+e.getMessage());
}
return false;
}
}
BaseDao
最新推荐文章于 2024-11-08 14:07:13 发布