溫馨提示×

jdbc工具類如何封裝

小億
85
2023-11-22 14:07:02
欄目: 編程語言

封裝JDBC工具類可以按照以下步驟進行:
1. 導入JDBC相關的包,如`java.sql`。
2. 創(chuàng)建一個數(shù)據(jù)庫連接的靜態(tài)方法,該方法用于建立與數(shù)據(jù)庫的連接,并返回一個`Connection`對象。
3. 創(chuàng)建一個執(zhí)行SQL語句的靜態(tài)方法,該方法接受兩個參數(shù):一個是`Connection`對象,一個是SQL語句字符串。該方法內部創(chuàng)建`Statement`對象,并使用它執(zhí)行SQL語句,然后返回一個`ResultSet`對象。
4. 創(chuàng)建方法用于關閉數(shù)據(jù)庫連接,該方法接受一個`Connection`對象作為參數(shù),并在方法內部關閉該連接。
5. 在需要使用數(shù)據(jù)庫的地方,調用上述封裝的方法進行數(shù)據(jù)庫操作。
下面是一個簡單的JDBC工具類的示例:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtils {

????public?static?Connection?getConnection(String?url,?String?username,?String?password)?{

????????Connection?connection?=?null;

????????try?{

????????????connection?=?DriverManager.getConnection(url,?username,?password);

????????}?catch?(SQLException?e)?{

????????????e.printStackTrace();

????????}

????????return?connection;

????}

????public?static?ResultSet?executeQuery(Connection?connection,?String?sql)?{

????????ResultSet?resultSet?=?null;

????????try?{

????????????Statement?statement?=?connection.createStatement();

????????????resultSet?=?statement.executeQuery(sql);

????????}?catch?(SQLException?e)?{

????????????e.printStackTrace();

????????}

????????return?resultSet;

????}

????public?static?void?closeConnection(Connection?connection)?{

????????try?{

????????????connection.close();

????????}?catch?(SQLException?e)?{

????????????e.printStackTrace();

????????}

????} }

使用該工具類的示例代碼如下:

import?java.sql.Connection;
import?java.sql.ResultSet;
import?java.sql.SQLException;
public?class?Main?{

????public?static?void?main(String[]?args)?{

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

????????String?username?=?“root”;

????????String?password?=?“password”;

????????Connection?connection?=?JdbcUtils.getConnection(url,?username,?password);

????????ResultSet?resultSet?=?JdbcUtils.executeQuery(connection,?“SELECT?*?FROM?users”);

????????try?{

????????????while?(resultSet.next())?{

????????????????int?id?=?resultSet.getInt(“id”);

????????????????String?name?=?resultSet.getString(“name”);

????????????????System.out.println("id:?"?+?id?+?",?name:?"?+?name);

????????????}

????????}?catch?(SQLException?e)?{

????????????e.printStackTrace();

????????}?finally?{

????????????JdbcUtils.closeConnection(connection);

????????}

????} }

注意:在使用JDBC時,應該注意異常處理和資源釋放,以確保程序的穩(wěn)定性和安全性。

0