刚开始接触j2ee的时候总是为数据库的开关连接问题而烦恼,虽然问题很简单却很是琐碎,于是干脆写成一个类将所有必要的基本操作全部总结进去,以后只要轻松的import一下就可以了啊:)菜鸟们enjoying!
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.Vector;
public class DBConnection {
//数据库属性
public static String dbDriverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
//其他驱动自己填写
public static String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName="DBNAME";
public static String dbUserID = "userid";
public static String dbUserPass = "userpassword";
public DBConnection() {
}
public void open() throws Exception{
open( dbDriverName, dbURL, dbUserID, dbUserPass);
}
/**
* 创建一个数据库连接
* @param driver
* JDBC驱动类
* @param url
* 数据库位置
* @param userID
* 数据库登录名
* @param password
* 数据库登录密码
* @throws Exception
* 创建数据库失败
*/
public void open(String driver, String url,
String userID, String password)throws Exception{
close();
Class.forName(driver);
connection = java.sql.DriverManager.getConnection(url, userID, password);
connected = true;
}
/**
* 关闭当前数据库连接
*/
public void close(){
if (connection == null )
return;
try{
if ( !connection.isClosed() )
connection.close();
}catch(Exception e){
}
connected = false;
}
/**
* 判断连接状态
* @return
* 连接返回true,否则返回false;
*/
public boolean isConnected(){
return connected;
}
public void executeInsert (String sql) throws Exception
{
check();
createStatement();
statement.execute(sql);
}
public void executeBatch(Vector sqls)throws Exception{
check();
createStatement();
for( int i = 0; i < sqls.size(); i++ ){
String sql = (String)sqls.get(i);
if ( sql.toLowerCase().trim().startsWith("select")){
throw new Exception("Batch 操作不支持Select操作");
}
statement.addBatch(sql);
}
statement.executeBatch();
}
public ResultSet executeSelect (String sql) throws Exception
{
check();
createStatement();
statement.execute(sql);
return statement.getResultSet();
}
public int executeUpdate (String sql) throws Exception
{
check();
createStatement();
statement.execute(sql);
return statement.getUpdateCount();
}
public int executeDelete (String sql) throws Exception
{
check();
createStatement();
statement.execute(sql);
return statement.getUpdateCount();
}
public void execute (String sql) throws Exception
{
check();
createStatement();
statement.execute(sql);
}
public void beginTrans ()throws Exception
{
check();
connection.setAutoCommit(false);
}
public void commit () throws Exception
{
check();
connection.commit();
}
public void rollback ()
{
try{
connection.rollback();
}catch(Exception e){
}
}
public boolean isConnectioned () throws Exception
{
return connected;
}
protected void check () throws Exception
{
if (!connected)
throw new Exception("没有创建数据库连接");
}
public void createStatement() throws Exception
{
if ( statement == null || connection.getAutoCommit() )
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
protected Connection connection = null;
protected boolean connected;
protected Statement statement;
}