Pages

Thursday, November 25, 2010

Test Derby connection using JAVA

import java.sql.*;

public class TestDatabase {


public static void main(String[] args) {
String driver = "org.apache.derby.jdbc.ClientDriver";
String dbName="myDB";
String connectionURL = "jdbc:derby://localhost:1527/"+dbName+";create=true;user=username;password=password";
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionURL);
try{
Statement st1 = conn.createStatement();
String sql = "CREATE TABLE TestTable ( id INT PRIMARY KEY, NAME VARCHAR(45) )";
st1.execute(sql);
                        sql = "INSERT INTO TestTable VALUES (100, 'HELLO WORLD'  )";
String query = "select * from TestTable ";
ResultSet rs = st1.executeQuery(query);
System.out.println("Result of " + query + ":");
while ( rs.next() ) {
int x = rs.getInt("ID");
System.out.println("Row " + rs.getRow() + ": " + x);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
conn.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

No comments:

Post a Comment