server|sql|sqlserver|資料|資料庫|資料庫連接
下面是以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) { } }}