JDBC のユーティリティ クラスをラッピングする方法
JDBCユーティリティークラスのカプセル化には、以下の手順があります。1. java.sqlなどのJDBC関連パッケージをインポートします。2. データベース接続を確立するために使用され、Connectionオブジェクトを返すデータベース接続の静的メソッドを作成します。3. ConnectionオブジェクトとSQLステートメント文字列の2つのパラメータを受け付けるSQLステートメントを実行する静的メソッドを作成します。このメソッドの内部ではStatementオブジェクトが作成され、これを使用してSQLステートメントを実行してからResultSetオブジェクトを返します。4. Connectionオブジェクトを受け取り、その接続を内部的に閉じるデータベース接続を閉じるために使用されるメソッドを作成します。5. データベースを使用する必要がある場合は、上記のカプセル化されたメソッドを呼び出してデータベース操作を実行します。以下は、単純な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);
}
} }
データベース接続時の例外処理とリソース解放でプログラムの安定性と安全性を確保する必要があります。