JDBC 的 HelloWorld 程序, 数据库访问MySQL


 import java.sql.*;
 /**
 * 第一个 JDBC 的 HelloWorld 程序, 数据库访问MySQL.
 *
 * @author [email protected]
 * @version 0.4 2008-06-17
 */
 public class JDBCHelloWorld {
 public static void main(String[] args) {
 // 1. 注册驱动
 try {
 Class.forName("com.mysql.jdbc.Driver");
 } catch (ClassNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }// Mysql 的驱动
 // 先定义变量,后使用和关闭
 Connection conn = null;// 数据库连接
 Statement stmt = null;// 数据库表达式
 ResultSet rs = null;// 结果集
 try {
 // 2. 获取数据库的连接
 conn = java.sql.DriverManager
 .getConnection("jdbc:mysql://localhost:3306/bookdb?useUnicode=true&characterEncoding=GBK","root", "admin");// root是用户名,密码为空
 // 3. 获取表达式
 stmt = conn.createStatement();
 // 执行插入数据的 SQL
 int row = stmt
 .executeUpdate("insert into books values('002', 'fanjf1教程1')");
 System.out.println("插入了 " + row);
 // 4. 执行 SQL
 rs = stmt.executeQuery("select * from books");
 // 5. 显示结果集里面的数据
 while (rs.next()) {
 System.out.println("编号=" + rs.getString("book_id"));
 System.out.println("书名=" + rs.getString("book_name"));
 }
 // 执行删除数据的 SQL, 被删除的记录的ID为7
 row = stmt.executeUpdate("delete from books where book_id = '001'");
 System.out.println("删除了 " + row);
 } catch (SQLException e) {
 e.printStackTrace();
 } finally {
 // 6. 释放资源,建议放在finally语句中确保都被关闭掉了
 try {
 rs.close();
 } catch (SQLException e) {
 }
 try {
 stmt.close();
 } catch (SQLException e) {
 }
 try {
 conn.close();
 } catch (SQLException e) {
 }
 }
 }
 }

猜你喜欢

转载自blog.csdn.net/jifeijixufly/article/details/5543439
今日推荐