?? basedao.java
字號:
/*
* s2jsp.lg.dao.impl.BaseDao.java
* 2007-7-18
* Dao的基類,使用JDBC連接數(shù)據庫、釋放資源、執(zhí)行sql,可以被其他Dao實現(xiàn)類繼承或實例化使用
*/
package s2jsp.lg.dao.impl;
import java.sql.*;
public class BaseDao {
public final static String DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; // 數(shù)據庫驅動
public final static String URL = "jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=bbs"; // url
public final static String DBNAME = "sa"; // 數(shù)據庫用戶名
public final static String DBPASS = "sa"; // 數(shù)據庫密碼
/**
* 得到數(shù)據庫連接
* @throws ClassNotFoundException
* @throws SQLException
* @return 數(shù)據庫連接
*/
public Connection getConn() throws ClassNotFoundException, SQLException{
Class.forName(DRIVER); //注冊驅動
Connection conn = DriverManager.getConnection(URL,DBNAME,DBPASS); //獲得數(shù)據庫連接
return conn ; //返回連接
}
/**
* 釋放資源
* @param conn 數(shù)據庫連接
* @param pstmt PreparedStatement對象
* @param rs 結果集
*/
public void closeAll( Connection conn, PreparedStatement pstmt, ResultSet rs ) {
/* 如果rs不空,關閉rs */
if(rs != null){
try { rs.close();} catch (SQLException e) {e.printStackTrace();}
}
/* 如果pstmt不空,關閉pstmt */
if(pstmt != null){
try { pstmt.close();} catch (SQLException e) {e.printStackTrace();}
}
/* 如果conn不空,關閉conn */
if(conn != null){
try { conn.close();} catch (SQLException e) {e.printStackTrace();}
}
}
/**
* 執(zhí)行SQL語句,可以進行增、刪、改的操作,不能執(zhí)行查詢
* @param sql 預編譯的 SQL 語句
* @param param 預編譯的 SQL 語句中的‘?’參數(shù)的字符串數(shù)組
* @return 影響的條數(shù)
*/
public int executeSQL(String preparedSql,String[] param) {
Connection conn = null;
PreparedStatement pstmt = null;
int num = 0;
/* 處理SQL,執(zhí)行SQL */
try {
conn = getConn(); // 得到數(shù)據庫連接
pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement對象
if( param != null ) {
for( int i = 0; i < param.length; i++ ) {
pstmt.setString(i+1, param[i]); // 為預編譯sql設置參數(shù)
}
}
num = pstmt.executeUpdate(); // 執(zhí)行SQL語句
} catch (ClassNotFoundException e) {
e.printStackTrace(); // 處理ClassNotFoundException異常
} catch (SQLException e) {
e.printStackTrace(); // 處理SQLException異常
} finally {
closeAll(conn,pstmt,null); // 釋放資源
}
return num;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -