JDBC连接数据库封装实现方法分享 (jdbc连接数据库封装)

JDBC是Java Database Connectivity的缩写,即Java数据库连接,是Java的一个标准的接口,定义了一套标准的访问数据库的接口。JDBC提供了一种基于SQL语句进行数据库操作的方式,使得Java程序能够访问各种类型的数据库。

JDBC连接数据库是Java开发中必不可少的一部分,但是每次使用JDBC连接数据库时都需要手动编写大量的重复代码,这不仅繁琐而且容易出错。因此,我们通常会将数据库的连接和操作封装起来,以减少代码的重复性,提高代码的重用性和可维护性。接下来,本文将介绍JDBC连接数据库封装实现方法的详细步骤。

实现步骤

1、定义一个数据库连接池类

为了封装数据库连接,我们需要定义一个连接池类,用于维护数据库连接。在该类中,我们需要定义一个数据库连接池的列表(List)和一个线程池(ExecutorService),在连接池初始化时,我们需要向连接池添加指定数量的数据库连接,同时创建一个线程池用于管理数据库连接的释放。连接池类的代码如下:

“`java

public class ConnectionPool {

private List pool;

private static final int DEFAULT_POOL_SIZE = 5;

private static final int MAX_POOL_SIZE = 10;

private static final int TIMEOUT = 5000;

private ConnectionPool() {

pool = new ArrayList(DEFAULT_POOL_SIZE);

for (int i = 0; i

pool.add(createConnection());

}

}

public static ConnectionPool getInstance() {

return ConnectionPoolHolder.INSTANCE;

}

private static class ConnectionPoolHolder {

private static final ConnectionPool INSTANCE = new ConnectionPool();

}

public synchronized Connection getConnection() {

int index = pool.size() – 1;

Connection connection = pool.remove(index);

try {

if (connection.isClosed()) {

connection = getConnection();

}

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

connection = getConnection();

}

return connection;

}

public synchronized void releaseConnection(Connection connection) {

if (pool.size() >= MAX_POOL_SIZE) {

try {

connection.close();

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

} else {

pool.add(connection);

}

}

private Connection createConnection() {

Connection connection = null;

try {

Class.forName(“com.mysql.jdbc.Driver”);

String url = “jdbc:mysql://localhost:3306/test”;

String user = “root”;

String password = “123456”;

connection = DriverManager.getConnection(url, user, password);

} catch (ClassNotFoundException | SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

return connection;

}

public void closePool() {

for (Connection connection : pool) {

try {

connection.close();

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

}

pool.clear();

}

}

“`

在该类中,我们使用了单例模式来保证全局只有一个ConnectionPool对象。在getConnection()方法中,我们从连接池中获取一个数据库连接,若该连接已关闭,则尝试从池中获取另一个连接;在releaseConnection()方法中,我们将数据库连接释放回连接池供其他线程使用;在createConnection()方法中,我们使用DriverManager获取一个数据库连接。

2、定义一个数据库操作类

除了连接池类之外,我们还需要定义一个数据库操作类,用于执行各种SQL语句。在该类中,我们需要定义一个ConnectionPool对象以获取数据库连接,同时定义一系列的执行SQL语句的方法。数据库操作类的代码如下:

“`java

public class DBHelper {

private ConnectionPool connectionPool;

public DBHelper() {

connectionPool = ConnectionPool.getInstance();

}

public ResultSet executeQuery(String sql) {

ResultSet resultSet = null;

try (Connection connection = connectionPool.getConnection();

PreparedStatement statement = connection.prepareStatement(sql)) {

resultSet = statement.executeQuery();

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

return resultSet;

}

public int executeUpdate(String sql) {

int rowsUpdated = 0;

try (Connection connection = connectionPool.getConnection();

PreparedStatement statement = connection.prepareStatement(sql)) {

rowsUpdated = statement.executeUpdate();

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

return rowsUpdated;

}

public int executeUpdate(String sql, List params) {

int rowsUpdated = 0;

try (Connection connection = connectionPool.getConnection();

PreparedStatement statement = connection.prepareStatement(sql)) {

int index = 1;

for (Object obj : params) {

statement.setObject(index, obj);

index++;

}

rowsUpdated = statement.executeUpdate();

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

return rowsUpdated;

}

}

“`

在该类中,我们使用了try-with-resources语句来自动关闭资源。executeQuery()方法用于执行SELECT语句,并返回一个ResultSet对象;executeUpdate()方法用于执行INSERT、UPDATE、DELETE语句,并返回受影响的行数;executeUpdate()方法还提供了一个可变参数的params列表,用于设置PreparedStatement中的参数。

3、测试连接池和数据库操作类

在完成了连接池和数据库操作类的定义之后,我们需要对其进行测试。在测试之前,我们需要在数据库中创建一个名为”test”的数据库,并在该数据库中创建一个名为”users”的表,其结构如下:

“`sql

CREATE TABLE `users` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(50) NOT NULL,

`age` int(11) NOT NULL,

PRIMARY KEY (`id`)

);

“`

在测试类中,我们需要通过DBHelper对象来执行各种SQL语句(查询、插入等),同时需要手动释放资源。测试代码如下:

“`java

public class TestJDBC {

public static void mn(String[] args) {

testConnectionPool();

testDBHelper();

}

private static void testConnectionPool() {

ConnectionPool connectionPool = ConnectionPool.getInstance();

for (int i = 0; i

Connection connection = connectionPool.getConnection();

if (connection != null) {

System.out.println(“Success: ” + connection);

} else {

System.out.println(“Fl: ” + i + “, ” + connection);

}

}

connectionPool.closePool();

}

private static void testDBHelper() {

DBHelper dbHelper = new DBHelper();

// insert

String sql = “INSERT INTO `users`(`name`, `age`) VALUES (‘Tom’, 20)”;

int rowsUpdated = dbHelper.executeUpdate(sql);

System.out.println(“Rows updated: ” + rowsUpdated);

// insert with parameters

sql = “INSERT INTO `users`(`name`, `age`) VALUES (?, ?)”;

List params = new ArrayList();

params.add(“Jerry”);

params.add(22);

rowsUpdated = dbHelper.executeUpdate(sql, params);

System.out.println(“Rows updated: ” + rowsUpdated);

// select

sql = “SELECT * FROM `users`”;

ResultSet resultSet = dbHelper.executeQuery(sql);

try {

while (resultSet.next()) {

System.out.println(“ID: ” + resultSet.getInt(“id”)

+ “, Name: ” + resultSet.getString(“name”)

+ “, Age: ” + resultSet.getInt(“age”));

}

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

try {

if (resultSet != null) {

resultSet.close();

}

} catch (SQLException e) {

System.out.println(“Error: ” + e.getMessage());

}

}

}

“`

在测试代码中,我们首先通过testConnectionPool()方法测试连接池的功能,可以看到在连接池已满的情况下,getConnection()方法会返回null。然后我们通过testDBHelper()方法测试DBHelper类的功能,可以看到在执行各种SQL语句时,我们不需要手动获取和释放数据库连接,这些操作已经被封装在DBHelper类的方法中了。

相关问题拓展阅读:

java 使用jdbc技术怎样连接同一个数据库,但有多个数据库名?

将连接封搭埋装起来 一个工厂类

public class ConnectionFactory {

private static String _url = null;

private static String _user = null;

private static String _pwd = null;

private static String _driver = null;

public ConnectionFactory() {

// TODO Auto-generated constructor stub

}

static {

_driver = DBConfig.getDBConfig().getValue(“driver”);

_user = DBConfig.getDBConfig().getValue(“user”);

_pwd = DBConfig.getDBConfig().getValue(“password”);

_url = DBConfig.getDBConfig().getValue(“url”);

}

public static Connection getConnection() throws SQLException {

try {

Class.forName(_driver);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

System.out.println(“注册驱动失败”);

e.printStackTrace();

throw new SQLException(“注册键租驱动失败”);

}

return DriverManager.getConnection(_url, _user, _pwd);

}

public static void release(Connection con, Statement stm, ResultSet rs) {

try {

if (con != null) {

con.close();

}

if (stm != null) {

con.close();

}

if (rs != null) {

rs.close();

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

然后再写一个配置文稿枝兆件

public class DBConfig {

private static DBConfig instance;

private static Properties info = new Properties();

private static String path = “dbconfig.properties”;

public DBConfig() {

// TODO Auto-generated constructor stub

readDBConfig();

}

private void readDBConfig() {

InputStream inputStream = null;

try {

if (!(new File(path).exists())) {

path = “./bin/” + path;

}

inputStream = new FileInputStream(path);

info.load(inputStream);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (inputStream != null) {

try {

inputStream.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

public synchronized static DBConfig getDBConfig() {

// 注意这里

if (instance == null) {

instance = new DBConfig();

}

return instance;

}

public String getValue(String key) {

return info.getProperty(key);

}

public static void main(String args) {

String driver = DBConfig.getDBConfig().getValue(“driver”);

String user = DBConfig.getDBConfig().getValue(“user”);

String pwd = DBConfig.getDBConfig().getValue(“password”);

String url = DBConfig.getDBConfig().getValue(“url”);

System.out.println(driver + ‘\n’ + user + ‘\n’ + pwd + ‘\n’ + url);

}

}

到时调用的时候

你将DBConfig中放在一个.file文件中 读出来 下面就是DBConfig文件:是sqlserver的

想连接什么数据库 把driver url改一下就OK了 到网上查

driver=com.microsoft.jdbc.sqlserver.SQLServerDriver

url=jdbc:microsoft:

user=sa

password=

ConnectionFactory.getConnection(); 这样一句话就连接上了

ConnectionFactory.release(); 就关闭相关对象了

关于jdbc连接数据库封装的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。


数据运维技术 » JDBC连接数据库封装实现方法分享 (jdbc连接数据库封装)