簡単なJDBC接続


package com.trimble;
import java.sql.*;

/** *//**
 *   JDBC     MySQL   
 * DataBase:test_d, table:mytest;
 */
public class MyDataBase {
    
    public static Connection getConnection() throws SQLException, 
            java.lang.ClassNotFoundException 
    {
        //   :  MySQL JDBC   
        Class.forName("com.mysql.jdbc.Driver");
        
        //     url,   MySQL       ,  ;studentinfo:    
        String url = "jdbc:mysql://localhost:3306/test_db";        
        String username = "root";
        String password = "root";
        
        //   :   MySQL          
        Connection con = DriverManager.getConnection(url, username, password);        
        return con;        
    }
    
    
    public static void main(String args[]) {
        try
        {
            //   :       con, con  Statement      sql_statement
            Connection con = getConnection();            
            Statement sql_statement = con.createStatement();
            String query = "select * from mytest";            
            ResultSet result = sql_statement.executeQuery(query);
            
            //            , Result        
            while (result.next()) 
            {
                int number          = result.getInt("id");

                //         
                System.out.println("=============== " + number );                
            }
            
            //       
            sql_statement.close();
            con.close();
            
        } catch(java.lang.ClassNotFoundException e) {
            //  JDBC  ,          
            System.err.print("ClassNotFoundException");
            //    
            System.err.println(e.getMessage());
        } catch (SQLException ex) {
            //              
            System.err.println("SQLException: " + ex.getMessage());
        }
    }

}