This is my code:
package logic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:./Database/Data", "Gustavo", "123456");
stmt = conn.createStatement();
stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY,NAME VARCHAR(255));");
stmt.execute("INSERT INTO TEST VALUES(1, 'John');");
ResultSet rs = stmt.executeQuery("select * from test");
while (rs.next()) {
System.out.println("id " + rs.getInt("id") + " name " + rs.getString("name"));
}
conn.close();
}
}
I can add the data and display it and if I run the code again (commenting the CREATE TABLE and INSERT INTO) it displays the data.
The problem is that when I go to the H2 console, it doesn't show anything unless I disconnect and reconnect. After I do that, it shows any changes made or data added to the database.
Is there a problem or that's how the H2 console works?
(I'm on Ubuntu 20.04, using vs code and gradle)
Edit: I solved it
The problem was in the code I was using it in embebed mode and it only allows one connection at a time. Once I changed it to server mode using:
String url = System.getProperty("user.dir") + "/Database/Data";
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/" + url, "Gustavo", "123456");