// Connect to Apache Derby database using Embedded driver import java.sql.Connection; import java.sql.DriverManager; public class TestConnection { public static void main(String[] args) throws Exception { Connection con = DriverManager.getConnection("jdbc:derby:c:\\dev\\java\\testdb;create=true"); System.out.println("Connected To Derby Database!"); con.close(); } }
// Create BOOKS table in APP schema import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class CreateTable { public static void main(String[] args) throws Exception { Connection con = DriverManager.getConnection("jdbc:derby:c:\\dev\\java\\testdb"); Statement st = con.createStatement(); st.executeUpdate("create table app.books (id int primary key GENERATED ALWAYS AS IDENTITY, title varchar(50), price int)"); con.close(); } }
// Insert a row into BOOKS table import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class AddBook { public static void main(String[] args) throws Exception { Connection con = DriverManager.getConnection("jdbc:derby:c:\\dev\\java\\testdb"); PreparedStatement ps = con.prepareStatement("insert into app.books(title,price) values(?,?)"); ps.setString(1,"Java Comp. Ref"); ps.setInt(2,500); ps.executeUpdate(); con.close(); } }
// List titles from BOOKS table import javax.sql.rowset.CachedRowSet; import javax.sql.rowset.RowSetFactory; import javax.sql.rowset.RowSetProvider; public class ListBooks { public static void main(String[] args) throws Exception { RowSetFactory factory = RowSetProvider.newFactory(); CachedRowSet crs = factory.createCachedRowSet(); crs.setUrl("jdbc:derby:c:\\dev\\java\\testdb"); crs.setCommand("select * from app.books"); crs.execute(); while(crs.next()) System.out.println(crs.getString("title")); crs.close(); } }