Java Reference
In-Depth Information
Display 19.12
Creating a Derby Embedded Database and Table (part 1 of 2)
1 import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.SQLException;
4 import java.sql.Statement;
5 public class CreateDB
6 {
7 private static final String driver =
"org.apache.derby.jdbc.EmbeddedDriver";
8 private static final String protocol = "jdbc:derby:";
9 public static void main(String[] args)
10 {
11 try
Load the embedded Derby driver.
12 {
13 Class.forName(driver).newInstance();
14 System.out.println("Loaded the embedded driver.");
15 }
16 catch (Exception err)
Must catch ClassNotFoundException,
InstantiationException, Illegal
AccessException.
17 {
18 System.err.println("Unable to load the embedded driver.");
19 err.printStackTrace(System.err);
20 System.exit(0);
21 }
22 String dbName = "BookDatabase";
23 Connection conn = null ;
24 try
25 {
26 System.out.println(
"Connecting to and creating the database...");
27 conn = DriverManager.getConnection(protocol + dbName +
";create=true");
28 System.out.println("Database created.");
Create a statement object
to run SQL statements.
29 Statement s = conn.createStatement();
Create a table called
“names” with three
i elds, 50 characters
for an author and an
integer author ID,
and 80 characters
for a URL, then insert
sample data.
30 s.execute("CREATE TABLE names" +
31 "(author varchar(50), author_id " +
"int, url varchar(80))");
32 System.out.println("Created 'names' table.");
33 System.out.println("Inserting authors.");
34 s.execute("INSERT INTO names " +
35 "VALUES ('Adams, Douglas', 1," +
"'http://www.douglasadams.com')");
(continued)
 
 
Search WWH ::




Custom Search