import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class BaseDao {
// 數據庫驅動
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//url
String url = "jdbc:sqlserver://數據庫ip:端口號;databaseName=數據庫名;";
//用戶名
String uname = "數據庫用戶名";
//密碼
String pwd = "數據庫密碼";
/**
* 獲得連接對象
* @return
*/
protected Connection getCon(){
//返回的連接
Connection con = null;
try {
//載入驅動
Class.forName(driver);
//得到連接
con = DriverManager.getConnection(url, uname, pwd);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
/**
* 關閉數據庫
* @param con
* @param stmt
* @param rs
*/
protected void closeDB(Connection con, Statement stmt, ResultSet rs){
if(rs != null){
try {
//關閉結果集
rs.close();
rs = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null){
try {
//關閉語句對象
stmt.close();
stmt = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con != null){
try {
//關閉連接對象
con.close();
con = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
protected void closeDB(Connection con, PreparedStatement pstmt, ResultSet rs){
if(rs != null){
//關閉結果集
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null){
try {
pstmt.close();
pstmt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null){
try {
con.close();
con = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
這個是我寫的壹個基本的連接sql2005數據庫的代碼,.! 不知道妳能不能用,! 妳看壹下吧, 連接的時候需要sqljdbc.jar數據庫驅動,!