Python Script to Connect to H2 Database and Perform an Insert
Here's a Python script that connects to the H2 in-memory database you specified and performs an insert operation:
import jaydebeapi
import uuid
def connect_to_h2():
# Database connection details from the log
jdbc_url = "jdbc:h2:mem:ffdf198a-28a2-44eb-8c99-b5326ea2494d"
username = "SA"
password = "" # Default password for H2 is empty
# Path to H2 JDBC driver (you'll need to download this)
h2_driver_path = "h2-2.1.214.jar" # Update this path to your actual H2 driver location
try:
# Connect to the database
conn = jaydebeapi.connect(
jclassname="org.h2.Driver",
url=jdbc_url,
driver_args=[username, password],
jars=h2_driver_path
)
print("Successfully connected to H2 database")
return conn
except Exception as e:
print(f"Error connecting to H2 database: {e}")
return None
def create_table_if_not_exists(conn):
try:
cursor = conn.cursor()
# Create a simple table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS example_table (
id VARCHAR(36) PRIMARY KEY,
data VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
print("Table checked/created successfully")
except Exception as e:
print(f"Error creating table: {e}")
def insert_data(conn, data_string):
try:
cursor = conn.cursor()
# Generate a UUID for the record
record_id = str(uuid.uuid4())
# Insert the data
cursor.execute(
"INSERT INTO example_table (id, data) VALUES (?, ?)",
(record_id, data_string)
)
conn.commit()
print(f"Successfully inserted data with ID: {record_id}")
except Exception as e:
print(f"Error inserting data: {e}")
def main():
# The string you want to insert
data_to_insert = "This is the data string to be inserted into the H2 database"
# Connect to the database
conn = connect_to_h2()
if conn:
try:
# Ensure the table exists
create_table_if_not_exists(conn)
# Insert the data
insert_data(conn, data_to_insert)
finally:
# Close the connection
conn.close()
print("Database connection closed")
if __name__ == "__main__":
main()
Prerequisites
-
You'll need to install the JayDeBeApi package:
pip install JayDeBeApi
-
You'll need to download the H2 JDBC driver (h2-*.jar) and place it in your project directory or specify the correct path in the script.
Notes
-
The script assumes the H2 database is still running and accessible at the JDBC URL from your logs.
-
If you're running this script separately from the Spring Boot application that created the database, the in-memory database might not be accessible. In-memory databases typically only exist for the duration of the application that created them.
-
The script creates a simple table called example_table if it doesn't exist, and then inserts your data string into it.
-
You can modify the table structure and insert statement as needed for your specific requirements.