「Java」org.apache.derby.jdbc.EmbeddedDriverでDBに接続するサンプルコード

Javaコード
package com.cftj;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class JavaDbDemo {
static Connection conn;

public static void main(String[] args) {
String driver = “org.apache.derby.jdbc.EmbeddedDriver”;
String connectionURL = “jdbc:derby:cftDatabase;create=true”;
String createString = “CREATE TABLE StudentTbl (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)”;
try {
Class.forName(driver);
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
stmt.executeUpdate(createString);

PreparedStatement insertSQL = conn.prepareStatement(“insert into StudentTbl values (?,?)”);

insertSQL.setString(1, args[0]);
insertSQL.setString(2, args[1]);

insertSQL.executeUpdate();

Statement stmt2 = conn.createStatement();
ResultSet rs = stmt2.executeQuery(“select * from StudentTbl”);
int num = 0;
while (rs.next()) {
System.out.println(++num + “: Name: ” + rs.getString(1) + “\n Address” + rs.getString(2));
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}