DriverManagerとJDBCUtils
3827 ワード
最初に、データベースへの接続をDriverManagerで実現することを学びました.その後、データベース接続プールの使用を学び、この方法はめったに使われませんでした.だからここに記録して、復習しやすいです.
一般的に、データベース接続には次のステップがあります.必要なurl、username、password、driver を準備するロード駆動 取得接続 操作 接続解除 DriverManagerの実現方式(一)
プロファイルがなく、すべてのものをソースコードに書きます.
DriverManagerの実現方式(二)
データベースの接続と解放を分離し、JDBCUtilsクラスを構成し、プロファイルを持ち、データベースの基本情報をプロファイルに書きます.JDBCUtilsクラスを使用して、データベースへの接続を完了します.
プロファイルjdbc.properties
一般的に、データベース接続には次のステップがあります.
プロファイルがなく、すべてのものをソースコードに書きます.
public static void main(String[] args) {
// url、username、password、driver
String url = "jdbc:mysql://localhost:3306/bookstore";
String username = "root";
String password = "1234";
String driver = "com.mysql.jdbc.Driver";
String sql = "";
Connection connection = null;
Statement statement = null;
ResultSet resulet = null;
try {
//
Class.forName(driver);
// connection
connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
// statement
statement = connection.createStatement();
// sql, result
resulet = statement.executeQuery(sql);
// result
while (resulet.next()) {
//
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// result
if (resulet != null) {
try {
resulet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// statement
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// connection
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
DriverManagerの実現方式(二)
データベースの接続と解放を分離し、JDBCUtilsクラスを構成し、プロファイルを持ち、データベースの基本情報をプロファイルに書きます.JDBCUtilsクラスを使用して、データベースへの接続を完了します.
public class JDBCTools {
public static Connection getConnection() throws Exception {
Properties properties = new Properties();
InputStream inStream = JDBCTools.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
properties.load(inStream);
// 1. 4 : user, password, jdbcUrl, driverClass
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driverClass = properties.getProperty("driverClass");
// 2. : Class.forName(driverClass)
Class.forName(driverClass);
// 3.
// DriverManager.getConnection(jdbcUrl, user, password)
//
Connection connection = DriverManager.getConnection(jdbcUrl, user,
password);
return connection;
}
public static void releaseDB(ResultSet resultSet, Statement statement,
Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
プロファイルjdbc.properties
user=root
password=1234
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///bookstore