JDBCプログラミング6ステップ

3008 ワード

最も原始的な書き方
import java.sql.*;
public class JDBCTest01{
    public static void main(String[] args){
        Connection conn=null;
        Statement stmt=null;
        try{
            //1.    
            Driver driver = new com.mysql.jdbc.Driver();
            DriverManager.registerDriver(driver);
            
            //String url="jdbc:mysql://ip:port/bjpowernode";
            String url="jdbc:mysql://localhost:3306/bjpowernode";
            String user="root";
            String password="333";
            //2.    
            conn=DriverManager.getConnection(url,user,password);
            //3.         
            stmt = conn.createStatement();
            //4.  sql
            String sql="insert into dept values(50,'renshibu','pudongxinqu')";
            //executeUpdate    DML   (insert update delete)
            //    "           "
            //        ,  int     
            int count = stmt.executeUpdate(sql);
            System.out.println(count==1? "ok" : "not ok");
            
        }catch(SQLException e){
            e.printStackTrace();
            
        }finally{
            //6.    
            //          ,    finally    
            //              stmt   conn
            //    try catch
            try{
                if(stmt != null)
                {
                    stmt.close();
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
            try{
                if(conn != null)
                {
                    conn.close();
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        
    }
    
}

登録ドライバの第2の方法
不要:DriverManager.registerDriver(new com.mysql.jdbc.Driver());反射機構だけが必要だforName("com.mysql.jdbc.Driver");この方法の実行は後のクラスのロードを招き、クラスのロード時に静的コードブロックが実行する、静的コードブロックの実行は駆動登録を完了する.(静的コードブロックはクラスのソースコードにあります)
この方法でよく用いられるのは、パラメータが1つの文字列であり、プロファイルに書き込むことができるためである.
プロファイルjdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
user=root
password=333

testでJAvaプログラムでは、次のように対応する値を取得できます.
ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
String driver=bundle.getString("driver");
String url=bundle.getString("url");
String user=bundle.getString("user");
String password=bundle.getString("password");

クエリー結果セットの処理
executeQueryは、DQL文専用のメソッドでResultSetタイプを返します.
ResultSet rs=null;
String sql="select empno,ename,sal from emp";
rs = stmt.executeQuery(sql);
while(rs.next()){
    //   ,     
    //             ,          
    int empno=rs.getInt("empno");
    //jdbc      1  
    //     
    String ename=rs.getString(2);
    double sal=rs.getDouble(3);
System.out.println(empno+","+ename+","+(sal+100));
}