简体   繁体   English

在不同程序中同时使用同一数据库

[英]Using the same database at the same time in different programs

I'm using the H2 Database Engine for java to have access to a database in my java programs. 我正在使用Java的H2数据库引擎来访问Java程序中的数据库。 I developed many java programs which use the same database. 我开发了许多使用相同数据库的Java程序。 The problem is that whenever I start such a program while another is already running it can't access the database because it is opened by the other program. 问题在于,每当我已经在另一个程序正在运行时启动该程序时,它就无法访问数据库,因为它是由另一个程序打开的。 Is there a way to let both programs have a connection to the database? 有没有办法让两个程序都连接到数据库? Whenever one program has to query the database the database should execute the query. 只要有一个程序必须查询数据库,数据库就应该执行查询。 In case it is executing the query of the other program the query should be executed directly after the query of the other program. 如果它正在执行另一个程序的查询,则应在另一个程序的查询之后直接执行查询。 Since my queries don't take long time the user wouldn't recognize that his program has to wait for a moment and everything would be fine. 由于我的查询不会花很长时间,因此用户不会意识到他的程序需要等待片刻,一切都会好起来的。

H2 server mode is what you want. H2服务器模式就是您想要的。

You need to have at least started the server this way for example: 您至少需要以这种方式启动服务器,例如:

org.h2.tools.Server.createTcpServer().start();

Then replace all the jdbc url with jdbc:h2://yourhost/yourdb , keeping in mind yourdb.h2.db will be located where the server was started. 然后,用jdbc:h2://yourhost/yourdb替换所有的jdbc URL,请记住yourdb.h2.db将位于启动服务器的位置。 I strongly advise not to use absolute path in your jdbc url, as it will give away the database path in case of hacking. 我强烈建议不要在您的jdbc url中使用绝对路径,因为在被黑客入侵的情况下,它将放弃数据库路径。

Last but not least: using the server mode for all has a performance penalty. 最后但并非最不重要的一点:对所有人使用服务器模式都会降低性能。 You might want to use mixed mode so that the 1st client will have almost embedded performances. 您可能要使用混合模式,以便第一个客户端几乎具有嵌入式性能。

To do this, just replace for this client the url with jdbc:h2:yourdb;AUTO_SERVER=TRUE . 为此,只需使用jdbc:h2:yourdb;AUTO_SERVER=TRUE替换此客户端的URL。 You could decide to use the same url for all clients as well: the 1st one to connect will be using embedded mode, the other clients will be using tcp performance. 您也可以决定对所有客户端都使用相同的url:要连接的第一个客户端将使用嵌入式模式,其他客户端将使用tcp性能。

Note that if you're using H2 > 1.4.*, you need to give absolute or relative path like this: jdbc:h2:./yourdb;AUTO_SERVER=TRUE . 请注意,如果您使用的H2> 1.4。*,则需要给出如下的绝对或相对路径: jdbc:h2:./yourdb;AUTO_SERVER=TRUE Note the ./ 注意./

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM