Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ## INITIALIZATION SECTION ##
- // Include the java SQL classes
- import java.sql.*;
- public class Database {
- public static void main(String[] args) throws SQLException {
- /* Strings fuer die Verbindung */
- String driver = "org.apache.derby.jdbc.EmbeddedDriver";
- String dbName = "testdb";
- String connectionURL = "jdbc:derby:" + dbName + ";create=true";
- //Attempts to establish a connection to the given database URL. The DriverManager attempts
- //to select an appropriate driver from the set of registered JDBC drivers.
- Connection conn = DriverManager.getConnection(connectionURL);
- Statement s = conn.createStatement();
- // ResultSet result;
- try { // Try-Block um eventuelle Fehler abzufangen
- // ## LOAD DRIVER SECTION ##
- try {
- Class.forName(driver); // Treiber laden
- System.out.println(driver + " loaded. ");
- } catch (java.lang.ClassNotFoundException e) {
- System.err.print("ClassNotFoundException: ");
- System.err.println(e.getMessage());
- }
- // ## INITIAL SQL SECTION ##
- //s.execute("insert into DBUSER(Name) values ('Glato')");
- ResultSet result = s.executeQuery("select * from DBUSER");
- while (result.next()) { // ausgabe aller Ergebnisse
- System.out.println(result.getString(1) + " "
- + result.getString(2));
- }
- s.close();
- conn.close();
- System.out.println("Closed connection");
- // ## DATABASE SHUTDOWN SECTION ##
- /***
- * In embedded mode, an application should shut down Derby. Shutdown
- * throws the XJ015 exception to confirm success.
- ***/
- if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) {
- boolean gotSQLExc = false;
- try {
- DriverManager.getConnection("jdbc:derby:;shutdown=true");
- } catch (SQLException se) {
- if (se.getSQLState().equals("XJ015")) {
- gotSQLExc = true;
- }
- }
- if (!gotSQLExc) {
- System.out.println("Database did not shut down normally");
- } else {
- System.out.println("Database shut down normally");
- }
- }
- // Beginning of the primary catch block: uses errorPrint method
- } catch (Throwable e) {
- /*
- * Catch all exceptions and pass them to the exception reporting
- * method
- */
- System.out.println(" . . . exception thrown:");
- errorPrint(e);
- }
- System.out.println("program ending.");
- }
- static void errorPrint(Throwable e) {
- if (e instanceof SQLException)
- SQLExceptionPrint((SQLException) e);
- else {
- System.out.println("A non SQL error occured.");
- e.printStackTrace();
- }
- } // END errorPrint
- static void SQLExceptionPrint(SQLException sqle) {
- while (sqle != null) {
- System.out.println("\n---SQLException Caught---\n");
- System.out.println("SQLState: " + (sqle).getSQLState());
- System.out.println("Severity: " + (sqle).getErrorCode());
- System.out.println("Message: " + (sqle).getMessage());
- sqle.printStackTrace();
- sqle = sqle.getNextException();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement