sam*_*nta 10 h2 embedded-database
我在servlet上下文启动时通过以下代码在H2数据库中创建一个内存数据库
void initDb() {
try {
webserver = Server.createWebServer().start();
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1","SA","");
InputStream in = getClass().getResourceAsStream("script.sql");
if (in == null) {
System.out.println("Please add the file script.sql to the classpath, package " + getClass().getPackage().getName());
} else {
RunScript.execute(conn, new InputStreamReader(in));
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT TO_CHAR(bday,'DD/MM/yyyy hh24:mi') FROM TEST2");
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
stat.close();
conn.commit();
conn.close();
}
//accessed using url jdbc:h2:tcp://localhost/mem:db1
try{
CachedRowSet crs = new DBConnector().executeQuery("select * from test2");
while(crs.next()){
System.out.println("ARGUMENT_NAME:"+crs.getString(1));
// System.out.println(",DATA_TYPE:"+crs.getString("DATA_TYPE"));
}
crs.close();
}catch(SQLException e){
e.printStackTrace();
}
} catch (Exception e) { //this exception gets throws connection failed!
System.out.println("Exception initializing memory H2 database"+e);
}
}
Run Code Online (Sandbox Code Playgroud)
我稍后在jdbc:h2:mem:db1同一个JVM中通过url访问,这也是有效的.但是,当我想通过jdbc:h2:tcp://localhost/mem:db1它访问它时,它不能在同一个JVM或不同的JVM中工作.
我实际上想要以嵌入模式运行系统并使用控制台查看内容.如果我在相同的servlet上下文启动方法中启动Web服务器,我可以看到控制台,但它仍然没有使用url连接到内存数据库jdbc:h2:tcp://localhost/mem:db1.
如果我使用命令行启动服务器
java -cp "WebContent/WEB-INF/lib/h2-1.3.148.jar;hsqldb.jar;%H2DRIVERS%;%CLASSPATH%" org.h2.tools.Console %*
and url as 'jdbc:h2:tcp://localhost/mem:db1'
Run Code Online (Sandbox Code Playgroud)
然后尝试连接,令人惊讶的是它连接但没有数据.似乎它正在创建一个单独的服务器并且它是一个不同的数据库.所以没有数据.
Tho*_*ler 21
要使内存数据库可用于其他进程,您需要在打开数据库的同一进程中启动TCP服务器.例:
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import org.h2.tools.Server;
public class TestMem {
public static void main(String... args) throws Exception {
// open the in-memory database within a VM
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:test");
conn.createStatement().execute("create table test(id int)");
// start a TCP server
// (either before or after opening the database)
Server server = Server.createTcpServer().start();
// .. use in embedded mode ..
// or use it from another process:
System.out.println("Server started and connection is open.");
System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
// now start the H2 Console here or in another process using
// java org.h2.tools.Console -web -browser
System.out.println("Press [Enter] to stop.");
System.in.read();
System.out.println("Stopping server and closing the connection");
server.stop();
conn.close();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20845 次 |
| 最近记录: |