注册 登录
编程论坛 J2EE论坛

[原创]连接数据库的bean

xiuyuan123 发布于 2006-05-08 13:31, 571 次点击
// substitute your own class path
package com.jspcafe.beans;

// standard classes to import when using jdbc
import java.sql.*;
import java.io.*;

public class OdbcBean {

// db is our connection object
Connection db = null;

// stmt will hold our jdbc statements
// i.e. sql and stored procedures
Statement stmt = null;

// result will hold the recordset
ResultSet result = null;

// default constructor
public OdbcBean() {
}

/*********************************************
* @dsn String for ODBC Datasource name
* @uid String for ODBC Datasource user name
* @pwn String for ODBC Datasource password
*/
public void OpenConn(
String dsn,
String uid,
String pwd) throws Exception {

try {
dsn = "jdbc:odbc:" + dsn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
db = DriverManager.getConnection(dsn, uid, pwd);
} catch (Exception e) {
e.printStackTrace();
}
}


/*********************************************
* @sproc String for sql statement or stored
* procedure
*/
public ResultSet getResults(String sproc)
throws Exception {

stmt = db.createStatement();
result = stmt.executeQuery(sproc);
return result;
}

/*********************************************
* @sproc String for sql statement or stored
* procedure
*/
public void execute(String sproc)
throws Exception {

stmt = db.createStatement();
stmt.execute(sproc);
}

// Don't forget to clean up!
public void CloseStmt()
throws Exception {

stmt.close();
stmt = null;
}

// Don't forget to clean up!
public void CloseConn()
throws Exception {

db.close();
db = null;
}

}
0 回复
1