📄 dbconn.java
字号:
package msg;
import dbpool.*;
import dbpool1.*;
import java.sql.*;
import java.io.*;
import java.util.*;
/**
*该类是数据库连接程序。功能包括初始化驱动,获取连接,获取查询结果,设置查询语句,<br>
*该类通过调用数据库连接池实现数据库访问
*/
public class DbConn
{
DBConnectionManager dbpool=null; //数据库连接池
DBConnectionManager1 dbpool1=null; //数据库连接池
public String SqlQuery;
public ResultSet result;
public Connection connection=null;
/**
*Constructor
*/
public DbConn()
{
connection = null;
dbpool= DBConnectionManager.getInstance(); //调用数据库连接池
dbpool1= DBConnectionManager1.getInstance(); //调用数据库连接池 (本地连接池)
}
/**
*从数据库连接池获取一个空闲的连接
*/
public void setConnection()
{
connection=dbpool.getConnection("mysql");
if(connection==null)
connection=dbpool.getConnection("mysql",3000); //超时3秒
if(connection==null){//如果依旧不能获取数据库连接 就把连接池初始化
dbpool.getDocInstance().reset();
connection=dbpool.getConnection("mysql");
if(connection==null)
connection=dbpool.getConnection("mysql",3000); //超时3秒
}
}
/**
*从数据库连接池获取一个空闲的连接
*/
public void setLocalConnection()
{
connection=dbpool1.getConnection("mysqlLocal");
if(connection==null)
connection=dbpool1.getConnection("mysqlLocal",3000); //超时3秒
if(connection==null){//如果依旧不能获取数据库连接 就把连接池初始化
dbpool1.getDocInstance().reset();
connection=dbpool1.getConnection("mysqlLocal");
if(connection==null)
connection=dbpool1.getConnection("mysqlLocal",3000); //超时3秒
}
}
/**
*获取连接。
*/
public Connection getConnection(){
return connection;
}
/**
*判断连接是否关闭
*/
public boolean isClosed() throws SQLException
{
if(connection==null)
return true;
return connection.isClosed();
}
/**
*关闭连接。
*/
public void closeConnection()
{
if(connection !=null){
dbpool.freeConnection("mysql",connection);
connection=null;
}
}
/**
*设置查询语句。
*/
public void setSqlQuery(String SqlQuery)
{
this.SqlQuery = SqlQuery;
}
/**
*获取查询结果。
*/
public ResultSet getResult() throws SQLException, IllegalArgumentException
{
if(SqlQuery==null || SqlQuery.equals(""))
{
throw new IllegalArgumentException("ERROR: An sql query has not been set!");
}
if(connection==null)
throw new SQLException("ERROR: connection is null!");
try
{
PreparedStatement select_stm=connection.prepareStatement(SqlQuery,
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
result=select_stm.executeQuery();
}
catch(Exception ex){}
return result;
}
/**
*执行修改或插入语句。
*/
public int executeUpdate() throws SQLException, IllegalArgumentException
{
if(SqlQuery==null || SqlQuery.equals(""))
{
throw new IllegalArgumentException("ERROR: An sql query has not been set!");
}
if(connection==null)
throw new SQLException("ERROR: connection is null!");
PreparedStatement statement = connection.prepareStatement(SqlQuery);
return statement.executeUpdate();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -