使用Java实现面向对象编程(9)
BaseDao:
package com.zb.dao.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 简化数据库的操作
* @author pc
*
*/
public class BaseDao {
private String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=student";
private String username = "sa";
private String password = "ok";
/**
* 获取数据库连接
* @return
*/
public Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/**
* 通用的增删改方法
* @param sql
* @param args
* @return
*/
public int executeUpdate(String sql,Object[] args){
Connection conn = this.getConnection();
int count = 0;
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
if(args != null){
for(int i = 0;i < args.length;i++){
pstmt.setObject(i+1, args[i]);
}
}
count = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
this.closeAll(conn, null, pstmt, null);
}
return count;
}
/**
* 关闭资源
* @param conn
* @param stmt
* @param pstmt
* @param rs
*/
public void closeAll(Connection conn,Statement stmt,PreparedStatement pstmt,ResultSet rs){
try {
if(rs != null){
rs.close();
}
if(pstmt != null){
pstmt.close();
}
if(stmt != null){
stmt.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}