下面是以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) {
}
}
} |