JDBC Tutorials - Herong's Tutorial Examples - v3.14, by Herong Yang
Creating Connections to Derby (Java DB) Network Server
This section describes how to create connections to Derby (Java DB) Network Server.
After I have my Derby (Java DB) 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 Derby (Java DB) server has been started in a command window like this:
herong> cd local herong> cd javadb 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 DerbyConnection.java herong> javac -cp $DERBY_HOME/lib/derbyclient.jar DerbyConnection.java herong> java -cp .;%DERBY_HOME%\lib\derbyclient.jar DerbyConnection herong> java -cp .:$DERBY_HOME/lib/derbyclient.jar DerbyConnection Derby connection ok.
The output confirms that the DriverManager class loaded the driver class and created a connection to the Derby (Java DB) 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 Derby (Java DB)
Derby (Java DB) Driver Features
Loading Derby JDBC Driver Classes
►Creating Connections to Derby (Java DB) Network Server
Derby (Java DB) Network Server and JDBC Driver Info
Derby (Java DB) - Creating New Tables
Derby (Java DB) - Inserting Data Rows to Existing Tables
Derby (Java DB) - Running SELECT Queries
Derby (Java DB) JDBC DataSource Objects
Derby (Java DB) - DML Statements
Derby (Java DB) - ResultSet Objects of Queries
Derby (Java DB) - PreparedStatement
Summary of JDBC Drivers and Database Servers