Java连接MySQL数据库

  1. import java.sql.SQLException;
  2. /**
  3.  * 数据库访问 MySQL.
  4.  * 
  5.  * @author yuzi
  6.  * @version
  7.  */
  8. public class T {
  9.     public static void main(String[] args) {
  10.         // 1. 注册驱动
  11.         try {
  12.             Class.forName("com.mysql.jdbc.Driver");
  13.         } catch (ClassNotFoundException e) {
  14.             // TODO Auto-generated catch block
  15.             e.printStackTrace();
  16.         }// Mysql 的驱动
  17.         // 先定义变量,后使用和关闭
  18.         java.sql.Connection conn = null;// 数据库连接
  19.         java.sql.Statement stmt = null;// 数据库表达式
  20.         java.sql.ResultSet rs = null;// 结果集
  21.         try {
  22.             // 2. 获取数据库的连接
  23.             conn = java.sql.DriverManager
  24.                     .getConnection(
  25.                             "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK",
  26.                             "root"null); // root是用户名,密码为空
  27.             // 3. 获取表达式
  28.             stmt = conn.createStatement();
  29.             // 执行插入数据的 SQL
  30.             stmt
  31.                     .executeUpdate("insert into Student(username, password,age) values('张三', '1234', 20)");
  32.             // 4. 执行 SQL
  33.             rs = stmt.executeQuery("select * from Student");
  34.             // 5. 显示结果集里面的数据
  35.             while (rs.next()) {
  36.                 System.out.println("编号=" + rs.getInt(1));
  37.                 System.out.println("学生姓名=" + rs.getString("username"));
  38.                 System.out.println("密码=" + rs.getString("password"));
  39.                 System.out.println("年龄=" + rs.getString("age"));
  40.             }
  41.             // 执行删除数据的 SQL
  42.             // stmt.executeUpdate("delete from Student");
  43.         } catch (SQLException e) {
  44.             e.printStackTrace();
  45.         } finally {
  46.             // 6. 释放资源,建议放在finally语句中确保都被关闭掉了
  47.             try {
  48.                 rs.close();
  49.             } catch (SQLException e) {
  50.             }
  51.             try {
  52.                 stmt.close();
  53.             } catch (SQLException e) {
  54.             }
  55.             try {
  56.                 conn.close();
  57.             } catch (SQLException e) {
  58.             }
  59.         }
  60.     }
  61. }
数据库:
CREATE TABLE Student (
  id int NOT NULL auto_increment,
  username varchar(200) NOT NULL,
  password varchar(20) NOT NULL,
  age int,
  PRIMARY KEY  (id)
)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值