1. 程式人生 > >使用JDBC基本步驟

使用JDBC基本步驟

1.JDBC

> JAVA Database Connectivity java 資料庫連線

* 為什麼會出現JDBC

> SUN公司提供的一種資料庫訪問規則、規範, 由於資料庫種類較多,並且java語言使用比較廣泛,sun公司就提供了一種規範,讓其他的資料庫提供商去實現底層的訪問規則。 我們的java程式只要使用sun公司提供的jdbc驅動即可。


2.使用JDBC的基本步驟

1. 註冊驅動

       DriverManager.registerDriver(new com.mysql.jdbc.Driver());

2. 建立連線

       //DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb");
           //2. 建立連線 引數一: 協議 + 訪問的資料庫 , 引數二: 使用者名稱 , 引數三: 密碼。
         connection = DriverManager.getConnection("jdbc:mysql://localhost/jdbc", "root", "root");

3. 建立statement

       //3. 建立statement , 跟資料庫打交道,一定需要這個物件
      statement = connection.createStatement();

4. 執行sql ,得到ResultSet

       //4. 執行查詢 , 得到結果集
           String sql = "select * from stu";
            resultSet = statement.executeQuery(sql);

5. 遍歷結果集

       //5. 遍歷查詢每一條記錄
          while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                
                System.out.println("id="+id+",name="+name+",age="+age);
            }

6. 釋放資源


       if(resultSet !=null){
                resultSet.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            resultSet = null;
        }