【MySQL使用技巧】JDBC连接

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

记得把Mysql-connector的jar加到Build Path中。
 
package org.bupt.jdbc;

/**
 * @author gnuhpc
 *         email: warmbupt@gmail.com
 *         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();
       

    }

}

 

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

posted @ 2012-12-21 17:17  gnuhpc  阅读(413)  评论(0编辑  收藏  举报