JDBC Tutorials - Herong's Tutorial Examples - v3.13, by Herong Yang
Creating Connections to Java DB (Derby) Network Server
This section describes how to create connections to Java DB (Derby) Network Server.
After I have my Java DB (Derby) started in Network Server mode, I am ready to try to create a connect object to access an existing database on the server. Here is my sample program showing you how to create a connection to access the TestDB:
/* DerbyConnection.java * Copyright (c) HerongYang.com. All Rights Reserved. */ import java.sql.*; public class DerbyConnection { public static void main(String [] args) { Connection con = null; try { // Connect with a url string con = DriverManager.getConnection("jdbc:derby://localhost/TestDB"); System.out.println("Derby connection ok."); con.close(); } catch (Exception e) { System.err.println("Exception: "+e.getMessage()); } } }
Make sure the Java DB (Derby) server has been started in a command window like this:
herong> cd lib herong> cd javadb herong> cd databases herong> ...\db\bin\startnetworkserver herong> %DERBY_HOME%\bin\startnetworkserver (or) herong> $DERBY_HOME/bin/startnetworkserver
Also make sure that "TestDB" database has been created in the server as shown in previous tutorials.
Now compile and run the example program, DerbyConnection.java, in another command window:
herong> javac -cp %DERBY_HOME%\lib\derbyclient.jar AutoLoadJdbcDriver.java herong> javac -cp $DERBY_HOME/lib/derbyclient.jar AutoLoadJdbcDriver.java herong> java -cp .;%DERBY_HOME%\lib\derbyclient.jar AutoLoadJdbcDriver herong> java -cp $DERBY_HOME/lib/derbyclient.jar AutoLoadJdbcDriver Derby connection ok.
The output confirms that the DriverManager class loaded the driver class and created a connection to the Java DB (Derby) server correctly:
If you have not created the "TestDB" database yet, or you did not start the server from the database folder, you will get an error like "Exception: The connection was refused because the database TestDB was not found."
Table of Contents
JDBC (Java Database Connectivity) Introduction
Installing and Running Java DB - Derby
Derby (Java DB) Driver Features
Loading Derby JDBC Driver Classes
►Creating Connections to Java DB (Derby) Network Server
Java DB (Derby) Network Server and JDBC Driver Info
Java DB (Derby) - Creating New Tables
Java DB (Derby) - Inserting Data Rows to Existing Tables
Java DB (Derby) - Running SELECT Queries
Derby (Java DB) JDBC DataSource Objects
Java DB (Derby) - DML Statements
Java DB (Derby) - ResultSet Objects of Queries
Java DB (Derby) - PreparedStatement
Summary of JDBC Drivers and Database Servers