🐈
0616週まとめ -Javaデータベース-
6/16週の研修(Javaデータベースプログラミング)における復習ノートです。
間違って理解しているところがあるかもしれないので、その際は指摘をお願いします。
データベース接続方法
-
- DriverManagerはJCBドライバを管理するための基本的なサービス
- java.sqlパッケージで提供(クライアントサーバーシステムで利用)
- データベース処理は以下の通り
- JDBCドライバのロード
- 接続の確立(Connectionオブジェクトの取得)
- SQL文の送信と結果の取得
- 接続の解除
-
- データベースと接続するためにはConnectionオブジェクトを取得
- 取得するためにはDriverManagerクラスのgetConnectionメソッドを使用
- try-with-resources文はtryブロックを抜けるときに自動的にリソースの解放を行う
(con.close();を明示的に記述する必要がない)
try(Connection con = DriverManager.getConnection(jdbcUrl, userId, password)){
//SQL文の送信と取得
}catch(SQLException e){
e.printStackTrace();
}
以上の記述がされていれば、データベースと接続することは可能
次章以降はデータベースの参照・更新方法やルール・効率的にSQL文を実行する方法を学んでいく
SQL文の実行
-
- RDBMSにSQL文を発行するには、java.sql.Statement系オブジェクトを使用
- Statement系オブジェクトは3種類(上から継承関係にある)
- Statement
- Prepared Statement
- Callable Statement
-
- StatementオブジェクトはStatement系オブジェクトのスーパークラス
- Statementオブジェクトを使用したSELECT文(参照)の実行手順は以下の通り
-
Statementオブジェクトの取得
ConnectionオブジェクトのcreateStatementメソッドを使用
-
SELECT文の実行
StatementオブジェクトのexecuteQueryメソッドを使用
実行後、java.sql.ResultSetオブジェクトが戻り値として返される
ResultSetは参照する場所をカーソルで示し、最初は先頭行の直前にある -
カーソルを参照行に移動
ResultSetオブジェクトのnextメソッドを使用する
boolean型の戻り値を返し、次に参照する行がなくなるとfalseを返す
(それまで繰り返し、結果の表示を続ける) -
列値の取得
参照行の値を取り出すのはResultSetオブジェクトのgetXxxxメソッド
(getString,getInt,getDouble等) -
ResultSetオブジェクトの解放
-
Statementオブジェクトの解放
-
public class Mame1{
public static void main (String[] args){
//jdbcUrl,userId,passwordの指定
//strSQLの指定(SELECT文)
try(Connection con = DriverManager.getConnection(jdbcUrl, userId, password)){
//1.Statementオブジェクトの取得
Statement stmt = con.createStatement;
//2.SELECT文の実行
ResultSet rs = stmt.executeQuery(strSQL);
//3.カーソルを参照行に移動
//4.列値の取得
while(rs.next()){
String custId = rs.getString("cust_id");
String custName = rs.getString("cust_name");
String custAddr = rs.getString("cust_addr");
System.out.println(custId + custName + custAddr);
}
//5.ResultSetの解放
//6.Statementの解放
rs.cose();
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
-
- Statementオブジェクトを使用したSELECT文(参照)の実行手順は以下の通り
-
Statementオブジェクトの取得
-
更新系SQL文の実行
StatementオブジェクトのexecuteUpdateメソッドを使用 -
Statementオブジェクトの解放
-
- Statementオブジェクトを使用したSELECT文(参照)の実行手順は以下の通り
public class Mame2{
public static void main(String[] args){
//jdbcUrl,userId,passwordの指定
//strSQLの指定(更新系)
try(Connnection con = DriverManager.getConnection(jdbcUrl, userId, password
//1.Statementオブジェクトの取得
Statement stmt = con.createStatement();
//2.更新系SQL文の実行
int line = stmt.executeUpdate(strSQL);
System.out.println(line "行更新しました");
//3.Statementオブジェクトの解放
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
-
- PreparedStatementオブジェクトを活用することで、コンパイル済みのSQL文を保持できる
- SQL文には入力パラメータを指定することができる
- PreparedStatementオブジェクトを使用したSELECT文の実行手順は以下の通り
- PreparedStatementオブジェクトの取得
- 入力パラメータの設定
- SQL文の実行
- 実行結果の利用
- 入力パラメータの再設定とSQL文の再実行
- PreparedStatementの解放
Discussion