记得把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/archive/2012/12/21/2828325.html如需转载请自行联系原作者