我已阅读有关在数据库中存储对象的 H2 文档。有特殊的 SQL 类型 OTHER 和方法 setObject
和 getObject
。我试过这段代码:
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("CREATE TABLE PUBLIC.foo (name VARCHAR(64) NOT NULL, data OTHER NULL);");
statement.execute();
} finally {
statement.close();
}
statement = null;
try {
statement = connection.prepareStatement("INSERT INTO PUBLIC.foo (name, data) VALUES(?,?);");
statement.setString(1, "lololo");
statement.setObject(2, new String[]{"foo", "bar"});
statement.execute();
}finally {
statement.close();
}
但我有异常(exception):
org.h2.jdbc.JdbcSQLException: Ше�тнадцатирична� �трока �одержит неше�тнадцатиричные �имволы: "(foo, bar)" Hexadecimal string contains non-hex character: "(foo, bar)"; SQL statement: INSERT INTO PUBLIC.foo (name, data) VALUES(?,?) -- (?1, ?2) [90004-191]
怎么了?
最佳答案
我相信这就是您要找的(甚至我也是)。
您只需在表格中创建一个类型为“other”的列。 请参见“创建表 testobj2(obj other)”
看看我的示例代码:
static String DB_DRIVER = "org.h2.Driver";
static String DB_CONNECTION = "jdbc:h2:./test2";
static String DB_USER = "";
static String DB_PASSWORD = "";
public static void benchmarkH2Inserts() {
try {
Class.forName(DB_DRIVER);
Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
String createQry = "create table testobj2(obj other)";
String insertQuery = "insert into testobj2(obj) values(?)";
String selectQuery = "select * from testobj2";
// dbConnection.setAutoCommit(false);
dbConnection.prepareStatement(createQry).executeUpdate();
long lStartTime = System.nanoTime();
for(int i=0; i<10000; i++) {
dbConnection.setAutoCommit(false);
CloudElement_Circuit obj = new CloudElement_Circuit();
obj.setNrm8DesignId(1230L);
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertQuery);
preparedStatement.setObject(1,obj);
preparedStatement.execute();
dbConnection.commit();
}
long lEndTime = System.nanoTime();
long output = lEndTime - lStartTime;
System.out.println("benchmarkH2Inserts() : Elapsed time in nanoseconds: " + output);
System.out.println("benchmarkH2Inserts() : Elapsed time in milliseconds: " + output / 1000000);
//Selecting
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectQuery);
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
CloudElement_Circuit obj = (CloudElement_Circuit) rs.getObject("obj");
System.out.println("Fetched Object : " + obj.getNrm8DesignId());
}
dbConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
请注意,“CloudElement_Circuit”是一个序列化类。 在这里查看“其他类型”:http://www.h2database.com/html/datatypes.html H2 示例:https://www.javatips.net/blog/h2-database-example
关于java - 如何将对象插入到h2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677229/