简体   繁体   中英

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. I developed many java programs which use the same database. 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.

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. I strongly advise not to use absolute path in your jdbc url, as it will give away the database path in case of hacking.

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 . 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.

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 . Note the ./

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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