📅  最后修改于: 2023-12-03 15:15:27.775000             🧑  作者: Mango
H2数据库是一款轻量级的Java数据库,具有高性能、开源免费、支持多种模式(嵌入式/服务器)、支持多种数据库标准(JDBC/ODBC/OLE)等优点。在通话应用中,H2数据库可以被用于存储通话记录、联系人信息等数据。本文将介绍如何在通话应用中使用H2数据库。
在Maven项目中引入以下依赖:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
在Gradle项目中引入以下依赖:
compile group: 'com.h2database', name: 'h2', version: '1.4.200'
使用以下代码连接数据库:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
private static final String DATABASE_URL = "jdbc:h2:~/test";
private static final String DATABASE_USER = "sa";
private static final String DATABASE_PASSWORD = "";
public static Connection connect() throws SQLException {
return DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD);
}
}
其中,DATABASE_URL为H2数据库的URL,~/test表示创建一个名为test的数据库,用户为sa,没有密码。需要注意的是,数据 URL 的前缀必须是 jdbc:h2:,或者是 jdbc:h2:mem:。如果是后者,则表示在内存中创建一个数据库。
使用以下代码创建表格:
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class TableCreator {
public static void createTables(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CALLS ("
+ "id INT PRIMARY KEY AUTO_INCREMENT,"
+ "caller_number VARCHAR(20),"
+ "callee_number VARCHAR(20),"
+ "start_time TIMESTAMP,"
+ "end_time TIMESTAMP,"
+ "duration INT"
+ ");";
statement.executeUpdate(sql);
}
}
其中,sql语句定义了一个名为CALLS、包含id、caller_number、callee_number、start_time、end_time、duration六个字段的表格。id字段为主键,自增,caller_number、callee_number为打电话者和接电话者的号码,start_time、end_time为通话开始和结束时间,duration为通话时长。
使用以下代码添加数据:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DataInserter {
public static void insertData(Connection connection, String callerNumber, String calleeNumber, LocalDateTime startTime, LocalDateTime endTime, int duration) throws SQLException {
String sql = "INSERT INTO CALLS (caller_number, callee_number, start_time, end_time, duration) VALUES (?, ?, ?, ?, ?);";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, callerNumber);
statement.setString(2, calleeNumber);
statement.setTimestamp(3, Timestamp.valueOf(startTime));
statement.setTimestamp(4, Timestamp.valueOf(endTime));
statement.setInt(5, duration);
statement.executeUpdate();
}
}
其中,callerNumber、calleeNumber为字符串类型的打电话者和接电话者号码,startTime、endTime为时间类型的通话开始和结束时间,duration为整型的通话时长。
使用以下代码查询数据:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DataSelecter {
public static List<Call> selectAllData(Connection connection) throws SQLException {
String sql = "SELECT * FROM CALLS;";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
List<Call> list = new ArrayList<>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String callerNumber = resultSet.getString("caller_number");
String calleeNumber = resultSet.getString("callee_number");
LocalDateTime startTime = resultSet.getTimestamp("start_time").toLocalDateTime();
LocalDateTime endTime = resultSet.getTimestamp("end_time").toLocalDateTime();
int duration = resultSet.getInt("duration");
Call call = new Call(id, callerNumber, calleeNumber, startTime, endTime, duration);
list.add(call);
}
return list;
}
public static Call selectData(Connection connection, int id) throws SQLException {
String sql = "SELECT * FROM CALLS WHERE id = ?;";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String callerNumber = resultSet.getString("caller_number");
String calleeNumber = resultSet.getString("callee_number");
LocalDateTime startTime = resultSet.getTimestamp("start_time").toLocalDateTime();
LocalDateTime endTime = resultSet.getTimestamp("end_time").toLocalDateTime();
int duration = resultSet.getInt("duration");
return new Call(id, callerNumber, calleeNumber, startTime, endTime, duration);
} else {
return null;
}
}
}
其中,selectAllData方法用于查询所有通话记录,selectData方法用于查询特定id的通话记录。查询结果以Call的形式封装。
通过本文介绍,读者应该掌握了在通话应用中如何使用H2数据库存储数据的方法。代码片段如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class H2Example {
private static final String DATABASE_URL = "jdbc:h2:~/test";
private static final String DATABASE_USER = "sa";
private static final String DATABASE_PASSWORD = "";
public static Connection connect() throws SQLException {
return DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD);
}
public static void createTables(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CALLS ("
+ "id INT PRIMARY KEY AUTO_INCREMENT,"
+ "caller_number VARCHAR(20),"
+ "callee_number VARCHAR(20),"
+ "start_time TIMESTAMP,"
+ "end_time TIMESTAMP,"
+ "duration INT"
+ ");";
statement.executeUpdate(sql);
}
public static void insertData(Connection connection, String callerNumber, String calleeNumber, LocalDateTime startTime, LocalDateTime endTime, int duration) throws SQLException {
String sql = "INSERT INTO CALLS (caller_number, callee_number, start_time, end_time, duration) VALUES (?, ?, ?, ?, ?);";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, callerNumber);
statement.setString(2, calleeNumber);
statement.setTimestamp(3, Timestamp.valueOf(startTime));
statement.setTimestamp(4, Timestamp.valueOf(endTime));
statement.setInt(5, duration);
statement.executeUpdate();
}
public static List<Call> selectAllData(Connection connection) throws SQLException {
String sql = "SELECT * FROM CALLS;";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
List<Call> list = new ArrayList<>();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String callerNumber = resultSet.getString("caller_number");
String calleeNumber = resultSet.getString("callee_number");
LocalDateTime startTime = resultSet.getTimestamp("start_time").toLocalDateTime();
LocalDateTime endTime = resultSet.getTimestamp("end_time").toLocalDateTime();
int duration = resultSet.getInt("duration");
Call call = new Call(id, callerNumber, calleeNumber, startTime, endTime, duration);
list.add(call);
}
return list;
}
public static Call selectData(Connection connection, int id) throws SQLException {
String sql = "SELECT * FROM CALLS WHERE id = ?;";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String callerNumber = resultSet.getString("caller_number");
String calleeNumber = resultSet.getString("callee_number");
LocalDateTime startTime = resultSet.getTimestamp("start_time").toLocalDateTime();
LocalDateTime endTime = resultSet.getTimestamp("end_time").toLocalDateTime();
int duration = resultSet.getInt("duration");
return new Call(id, callerNumber, calleeNumber, startTime, endTime, duration);
} else {
return null;
}
}
public static void main(String[] args) {
try {
Connection connection = connect();
createTables(connection);
insertData(connection, "123", "456", LocalDateTime.now().minusHours(1), LocalDateTime.now(), 3600);
List<Call> calls = selectAllData(connection);
for (Call call : calls) {
System.out.println(call);
}
Call call = selectData(connection, 1);
System.out.println(call);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private static class Call {
private int id;
private String callerNumber;
private String calleeNumber;
private LocalDateTime startTime;
private LocalDateTime endTime;
private int duration;
public Call(int id, String callerNumber, String calleeNumber, LocalDateTime startTime, LocalDateTime endTime, int duration) {
this.id = id;
this.callerNumber = callerNumber;
this.calleeNumber = calleeNumber;
this.startTime = startTime;
this.endTime = endTime;
this.duration = duration;
}
@Override
public String toString() {
return "Call{" +
"id=" + id +
", callerNumber='" + callerNumber + '\'' +
", calleeNumber='" + calleeNumber + '\'' +
", startTime=" + startTime +
", endTime=" + endTime +
", duration=" + duration +
'}';
}
}
}