The past few days I have been consumed with trying to figure out how Derby works. Derby is Java’s DBMS coded entirely in Java. I want to use Derby as part of the deliciousBlogger project to manage profile and scheduling information.
Derby has some very cool features if you are developing with Java. You are able to start it up as an embedded or server database. The embedded mode means you dont need a separate process to be running for the database system. It will run in the same space as the JVM. From what I have figured out you can pretty much do all the basic functions as other database servers though not always the same way. It does support core SQL commands to keep it standard.
I finally figured out how to start up the database in embedded mode (or at least i think it is); create a table; insert a few items; then query the table and print out the results.
package model;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.derby.drda.NetworkServerControl;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
*
* @author leadiv
*/
public class testing {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
NetworkServerControl server;
Connection conn;
try {
server = new NetworkServerControl(InetAddress.getByName(“localhost”), 1527);
server.start(null);
System.out.println(server.getSysinfo());
String nsURL=”jdbc:derby://localhost:1527/testing;create=true”;
java.util.Properties props = new java.util.Properties();
props.setProperty(“user”,”dbo1337″);
props.setProperty(“password”,”fnpbz”);
/*
If you are running on JDK 6 or higher, you do not
need to invoke Class.forName(). In that environment, the
ClientDriver loads automatically.
*/
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
conn = DriverManager.getConnection(nsURL, props);
/*interact with Derby*/
Statement s = conn.createStatement();
s.execute(“create table \”MYTABLE\” (\”ID\” INTEGER not null primary key, \”NAME\” VARCHAR(50))”);
s.execute(“insert into mytable values(1, ‘Paul’)”);
s.execute(“insert into mytable values(2, ‘Ashley’)”);
ResultSet rs = s.executeQuery(“select NAME from MYTABLE”);
while (rs.next()) {
System.out.println(“Name: ” + rs.getString(1));
}
rs.close();
s.close();
conn.close();
server.shutdown();
} catch(Exception ex) {
Logger.getLogger(ProfileSQL.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
Here are some links talking about Derby: Java Databasing with Derby, Derby’s Documentation