jdbc數據庫連接 實現hellojava

  JDBC Hello world 收藏
記得把Mysql-connector的jar加到Build Path中。

package org.bupt.jdbc;

/**
 * @author gnuhpc
 *         email: [email protected]
 *         blog:  http://blog.csdn.net/gnuhpc
 * @date 2010-1-6
 */
import java.sql.SQLException;

public class JDBCHelloWorld {

    /**
     * @param args
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // 1. 註冊驅動
        Class.forName("com.mysql.jdbc.Driver");// Mysql 的驅動
      
        // 2. 獲取數據庫的連接
        java.sql.Connection conn = java.sql.DriverManager.getConnection(
                "jdbc:mysql://localhost/publications?useUnicode=true&characterEncoding=GBK", "root", "passw0rd");
      
        // 3. 獲取表達式
        java.sql.Statement stmt = conn.createStatement();
      
        // 4. 執行 SQL
        java.sql.ResultSet rs = stmt.executeQuery("select * from books");
      
        // 5. 顯示結果集裏面的數據
        while(rs.next()) {
            System.out.println(rs.getInt(1));
            System.out.println(rs.getString("pages"));
            System.out.println(rs.getString("title"));
        }
      
        // 執行插入數據的 SQL
        //stmt.executeUpdate("insert into user values(2, '345', 'Linux Kernel')");
      
        // 6. 釋放資源
        rs.close();
        stmt.close();
        conn.close();
      

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章