1. 程式人生 > >01.JDBC操作資料庫-快速入門操作

01.JDBC操作資料庫-快速入門操作

/**
     * 簡單入門操作
     * 注:先將mysql-connector-java-5.1.36.jar 構建 Build Path環境當中去
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        //1.載入MySQL資料庫驅動包
        Class.forName("com.mysql.jdbc.Driver");
        //2.連線MySQL資料庫伺服器
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java", "root", "root");
        
//3.建立執行語句物件 Statement st = conn.createStatement(); //4.執行語句 st.executeUpdate("INSERT INTO `student` SET name='劉詩華 77154113',age=28"); //5.釋放資源 st.close(); conn.close(); }

 

    /**
     * JDBC查詢學生表
     * @param args
     * @throws Exception 
     
*/ public static void main(String[] args) throws Exception { //1.載入MySQL資料庫驅動包 Class.forName("com.mysql.jdbc.Driver"); //2.連線MySQL資料庫伺服器 Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java", "root", "root"); //3.建立執行語句物件 Statement st = conn.createStatement();
//4.執行語句 ResultSet rs = st.executeQuery("SELECT * FROM `student` ORDER BY id asc"); //rs當前是否指向資料表的某一行資料 如果有,則返true while(rs.next()) { System.out.println("學生姓名:"+rs.getString("name")+" 年齡:"+rs.getLong("age")); } //5.釋放資源 rs.close(); st.close(); conn.close(); //學生姓名:劉詩華 年齡:28 //學生姓名:羅蘭 年齡:27 }