public class JDBCHelloWorld {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
// 1. 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// Mysql 的驱动
// 2. 获取数据库的连接
java.sql.Connection conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=GBK", "root", null);
// 3. 获取表达式
java.sql.Statement stmt = conn.createStatement();
// 4. 执行 SQL
java.sql.ResultSet rs = stmt.executeQuery("select * from user");
// 5. 显示结果集里面的数据
while(rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.println(rs.getString("age"));
System.out.println();
}
// 执行插入数据的 SQL
stmt.executeUpdate("insert into user values(2, 'chinese', 'password', 25)");
// 6. 释放资源
rs.close();
stmt.close();
conn.close();
}
}