- H2数据库教程
- H2数据库 - 首页
- H2数据库 - 简介
- H2数据库 - 安装
- H2数据库 - 数据操作
- H2数据库 - 查询
- H2数据库 - 插入
- H2数据库 - 更新
- H2数据库 - 删除
- H2数据库 - 备份
- H2数据库 - 调用
- H2数据库 - 解释
- H2数据库 - 合并
- H2数据库 - 显示
- H2数据库 - 数据定义
- H2数据库 - 创建
- H2数据库 - 修改
- H2数据库 - 删除
- H2数据库 - 截断
- H2数据库 - 提交
- H2数据库 - 授权
- H2数据库 - 保存点
- H2数据库 - 回滚
- H2数据库 - JDBC连接
- H2数据库有用资源
- H2数据库 - 快速指南
- H2数据库 - 有用资源
- H2数据库 - 讨论
H2数据库 - JDBC连接
H2是一个JAVA数据库。我们可以使用JDBC与该数据库进行交互。在本章中,我们将了解如何使用JDBC连接H2数据库以及对H2数据库进行CRUD操作。
通常,创建JDBC连接需要五个步骤。
步骤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。我们可以从C:\Program Files (x86)\H2\bin文件夹获取此jar文件。
创建表
在这个例子中,我们将编写一个创建表的程序。考虑一个名为Registration的表,它包含以下字段。
| 序号 | 列名 | 数据类型 | 非空 | 主键 |
|---|---|---|---|---|
| 1 | ID | 数字 | 是 | 是 |
| 2 | 名 | Varchar(255) | 否 | 否 |
| 3 | 姓 | Varchar(255) | 否 | 否 |
| 4 | 年龄 | 数字 | 否 | 否 |
以下是一个名为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 | 名 | 姓 | 年龄 |
|---|---|---|---|
| 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!