-Check the JDK version -Set environment variables (so that the Java app can recognize the JDBC driver) https://www.agtech.co.jp/html/v11manuals/11.20/jdbc/jdbc-2-2.html (Click here for the information) https://netbeans.org/competition/win-with-netbeans/mysql-client_ja.html (For NetBeans) -Check the appropriate setting method for JDBC driver, etc. http://www.ne.jp/asahi/hishidama/home/tech/java/javadb.html ・ If you search for Derby JDBC, you will find a powerful site. -The user ID and password of the Derby database must be set to "APP".
The following is an example of outputting data from the database. The following outputs data from a database that has a table like Table 1.
Table 1 EMPLOYEES
| EMP_NO | EMP_NAME | 
|---|---|
| 1 | HOGE | 
| 2 | HORII | 
Example 1 Writing a JDBCcon class
import java.sql.*;
 public class JDBCcon {
     public static void main (String[] args){      
        Statement stmt = null;
        ResultSet rs = null;
        Connection con = null;
        
        try{
        //Step 1 Driver registration
        Class.forName("org.apache.derby.jdbc.ClientDriver");
         
        //Step 2 Designate the database
        String url = "jdbc:derby://localhost:1527/EmployeeDB";
        
        //Step 3 Establish a connection to the database
        con = DriverManager.getConnection(url,"APP","APP");
        
        //Step 4 Create a statement
        stmt = con.createStatement();
        
        //Step 5:SQL execution
        String sql ="SELECT * FROM EMPLOYEES";
         
        rs = stmt.executeQuery(sql);
        
        //Step 6:Processing results
          while (rs.next()){
            System.out.println("EMP_NO = " + rs.getString(1));
            System.out.println("EMP_NAME = " + rs.getString(2));
            System.out.println();
          }
        
        } catch(ClassNotFoundException e){
          System.out.println(e.getMessage());
          e.printStackTrace();
        } catch(SQLException e){
          System.out.println(e.getMessage());
          e.printStackTrace();
          
        //Step 7:Exit JDBC object
        } finally{
          try{
            if(rs != null) rs.close();
            if(stmt != null) stmt.close();
            if(con != null) con.close();
          }catch (SQLException e){}
        }    
    }
}
Example 2 Execution result
run:
EMP_NO = 1
EMP_NAME = HOGE      
EMP_NO = 2
EMP_NAME = HORII     
Postscript: From JDBC 4.0 of JDK 1.6, it seems to automatically load the driver in the classpath. Thank you for pointing out.
Recommended Posts