H2-database-jdbc-connection
H2データベース-JDBC接続
H2はJAVAデータベースです。 JDBCを使用して、このデータベースと対話できます。 この章では、H2データベースでJDBC接続を作成し、H2データベースでCRUD操作を作成する方法について説明します。
一般に、JDBC接続を作成するには5つの手順があります。
- ステップ1 *-JDBCデータベースドライバーの登録。
Class.forName ("org.h2.Driver");
- ステップ2 *-接続を開きます。
Connection conn = DriverManager.getConnection ("jdbc:h2:~/test", "sa","");
- ステップ3 *-ステートメントの作成。
Statement st = conn.createStatement();
- ステップ4 *-ステートメントを実行し、結果セットを受け取ります。
Stmt.executeUpdate("sql statement");
- ステップ5 *-接続を閉じます。
conn.close();
完全なプログラムを作成する前に、* h2-1.4.192.jarファイル*をCLASSPATHに追加する必要があります。 この jar は、フォルダー C:\ Program Files(x86)\ H2 \ bin から取得できます。
テーブルを作成
この例では、テーブルを作成するためのプログラムを作成します。 次のフィールドを持つ Registration という名前のテーブルを考えてください。
S.No | Column Name | Data Type | NOT NULL | Primary Key |
---|---|---|---|---|
1 | ID | Number | Yes | Yes |
2 | First | Varchar(255) | No | No |
3 | Last | Varchar(255) | No | No |
4 | Age | Number | No | No |
以下は、 H2jdbcCreateDemo という名前のプログラム例です。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcCreateDemo {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 3: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
//STEP 4: Clean-up environment
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try{
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}//nothing we can do
try {
if(conn!=null) conn.close();
} catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
上記のプログラムをH2jdbcCreateDemo.javaに保存します。 コマンドプロンプトで次のコマンドを実行して、上記のプログラムをコンパイルして実行します。
\>javac H2jdbcCreateDemo.java
\>java H2jdbcCreateDemo
上記のコマンドは、次の出力を生成します。
Connecting to database...
Creating table in given database...
Created table in given database...
Goodbye!
この実行後、H2 SQLインターフェイスを使用して作成されたテーブルを確認できます。
レコードを挿入
この例では、レコードを挿入するためのプログラムを作成します。 テーブルRegistrationに次のレコードを挿入しましょう。
ID | First | Last | Age |
---|---|---|---|
100 | Zara | Ali | 18 |
101 | Mahnaz | Fatma | 25 |
102 | Zaid | Khan | 30 |
103 | Sumit | Mital | 28 |
以下は、 H2jdbcInsertDemo という名前のプログラム例です。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcInsertDemo {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");
//STEP 3: Execute a query
stmt = conn.createStatement();
String sql = "INSERT INTO Registration " + "VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
//STEP 4: Clean-up environment
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}//nothing we can do
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
上記のプログラムをH2jdbcInsertDemo.javaに保存します。 コマンドプロンプトで次のコマンドを実行して、上記のプログラムをコンパイルして実行します。
\>javac H2jdbcInsertDemo.java
\>java H2jdbcInsertDemo
上記のコマンドは、次の出力を生成します。
Connecting to a selected database...
Connected database successfully...
Inserted records into the table...
Goodbye!
レコードを読む
この例では、レコードを読み取るためのプログラムを作成します。 テーブル Registration からすべてのレコードを読み取ってみましょう。
以下は、 H2jdbcRecordDemo という名前のプログラム例です。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcReadDemo {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 3: Execute a query
System.out.println("Connected database successfully...");
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 4: Extract data from result set
while(rs.next()) {
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 5: Clean-up environment
rs.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}//nothing we can do
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
上記のプログラムをH2jdbcReadDemo.javaに保存します。 コマンドプロンプトで次のコマンドを実行して、上記のプログラムをコンパイルして実行します。
\>javac H2jdbcReadDemo.java
\>java H2jdbcReadDemo
上記のコマンドは、次の出力を生成します。
Connecting to a selected database...
Connected database successfully...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!
レコードを更新する
この例では、レコードを更新するプログラムを作成します。 テーブル Registration からすべてのレコードを読み取ってみましょう。
以下は、 H2jdbcUpdateDemo という名前のプログラム例です。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcUpdateDemo {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
//Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to a database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 3: Execute a query
System.out.println("Connected database successfully...");
stmt = conn.createStatement();
String sql = "UPDATE Registration " + "SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);
//Now you can extract all the records
//to see the updated records
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}//nothing we can do
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
上記のプログラムをH2jdbcUpdateDemo.javaに保存します。 コマンドプロンプトで次のコマンドを実行して、上記のプログラムをコンパイルして実行します。
\>javac H2jdbcUpdateDemo.java
\>java H2jdbcUpdateDemo
上記のコマンドは、次の出力を生成します。
Connecting to a selected database...
Connected database successfully...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!
レコードを削除する
この例では、レコードを削除するプログラムを作成します。 テーブル Registration からすべてのレコードを読み取ってみましょう。
以下は、 H2jdbcDeleteDemo という名前のプログラム例です。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcDeleteDemo {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
//Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 3: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "DELETE FROM Registration " + "WHERE id = 101";
stmt.executeUpdate(sql);
//Now you can extract all the records
//to see the remaining records
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}//nothing we can do
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
上記のプログラムをH2jdbcDeleteDemo.javaに保存します。 コマンドプロンプトで次のコマンドを実行して、上記のプログラムをコンパイルして実行します。
\>javac H2jdbcDeleteDemo.java
\>java H2jdbcDeleteDemo
上記のコマンドは、次の出力を生成します。
Connecting to a selected database...
Connected database successfully...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Goodbye!