Java how to work with derby in embedded mode using jdbc
Apache Derby is a lightweight, open-source database management system that can be used with Java. Derby can be used in two modes - embedded mode and network client-server mode. In this guide, we will discuss how to use Derby in embedded mode using JDBC.
Here are the steps to work with Derby in embedded mode:
Download and install Derby on your machine. You can download Derby from the official Apache Derby website. Once you have downloaded the Derby distribution, extract it to a directory of your choice.
Create a new Java project in your IDE of choice.
Add the Derby JDBC driver to your project. The Derby JDBC driver is located in the "lib" folder of the Derby distribution. Add the following code to your project to load the driver:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
- Create a connection to the Derby database. To create a connection to the Derby database, you will need to provide a JDBC URL that specifies the path to the database on your machine. Here is an example of how to create a connection to a database named "mydatabase" located in the directory "C:\mydirectory":
String url = "jdbc:derby:C:/mydirectory/mydatabase;create=true"; Connection connection = DriverManager.getConnection(url);
Note that the "create=true" parameter tells Derby to create the database if it does not already exist.
- Use the connection to interact with the database. Once you have a connection to the database, you can use it to execute SQL statements and interact with the database. Here is an example of how to create a table:
Statement statement = connection.createStatement(); String sql = "CREATE TABLE mytable (id INT PRIMARY KEY, name VARCHAR(50))"; statement.executeUpdate(sql);
You can execute other SQL statements in a similar way.
- Close the connection. Once you are finished using the connection, you should close it to free up system resources:
connection.close();
That's it! With these steps, you can use Derby in embedded mode using JDBC to create and interact with a database from your Java program.