Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

H2 database error: Database may be already in use: "Locked by another process"

Tags:

java

database

h2

I am trying to use the H2 database from a Java application.

I created the database and its tables through the H2 Console and then I try to connect from Java using

Connection con = DriverManager.getConnection("jdbc:h2:~/dbname", "username", "password");

However I receive the following error:

Exception in thread "main" org.h2.jdbc.JdbcSQLException: Database may be already in use: "Locked by another process". Possible solutions: close all other connection(s); use the server mode [90020-161]

I tried to delete the dbname.lock.db file but it is automatically re-created.

How can I unlock the database to use it from my Java program?

like image 407
Vasilis Avatar asked Nov 16 '11 21:11

Vasilis


2 Answers

H2 is still running (I can guarantee it). You need to use a TCP connection for multiple users such as ->

<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/>

OR

DriverManager.getConnection("jdbc:h2:tcp://localhost/server~/dbname","username","password");

It also means you need to start the server in TCP mode. Honesetly, it is pretty straight forward in the documentation.

Force kill the process (javaw.exe for Windows), and make sure that any application that might have started it is shut down. You have an active lock.

like image 185
Daniel B. Chapman Avatar answered Oct 13 '22 08:10

Daniel B. Chapman


I had the same problem. in Intellj, when i want to use h2 database when my program was running i got the same error. For solve this problem i changed the connection url from

spring.datasource.url=jdbc:h2:file:~/ipinbarbot

to:

spring.datasource.url=jdbc:h2:~/ipinbarbot;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE

And then my problem gone away. now i can connect to "ipinbarbot" database when my program is. If you use Hibernate, also don't forget to have:

spring.jpa.hibernate.ddl-auto = update

goodluck

like image 24
Saman Salehi Avatar answered Oct 13 '22 07:10

Saman Salehi