下面是以SQLServer為例編寫一個簡單的數據庫連接工具類,把它封裝到web項目的(WEB-INF/classes/)目錄下,在Java或JSP頁面引入就可以實現了.
ODBC名稱:mysql;
用戶名:dxaw;
密 碼:123;
方法executeUpdate():對數據庫更新;
方法executeQuery():通過SQL語句返回記錄集;
代碼如下:
//類conn.db.conndb.java
package conn.db;
import java.sql.*;
public class conndb {
Connection conn;
ResultSet rs;
private int count;
public conndb() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception ex) {}
}
public ResultSet executeQuery(String sql){
try {
conn=DriverManager.getConnection("Jdbc:Odbc:mysql","dxaw","123");
Statement stat=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs=stat.executeQuery(sql);
} catch (Exception ex1) {
}
return rs;
}
public void executeUpdate(String sql){
try {
conn = DriverManager.getConnection("Jdbc:Odbc:mysql", "dxaw","123");
Statement stat=conn.createStatement();
stat.executeQuery(sql);
} catch (Exception ex2) {
}
}
}