2021-06-28

数据库jdbc

在这里插入图片描述

1. 配置信息

String name="root"; String psw="123456"; String URL="jdbc:mysql://localhost:3306/system?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=false";

2. 加载驱动

  Class.forName("com.mysql.cj.jdbc.Driver");

3. 连接数据库

  Connection connection= DriverManager.getConnection(URL,name,psw);

4. 向数据库发送sql的statement 对象

 Statement statement=connection.createStatement();

5. 编写sql 语句—增删改查等、

   String sql="select * from `system`.tb";

6. 执行sql语句

ResultSet rs=statement.executeQuery(sql);
 while (rs.next()){
            System.out.println("id="+rs.getObject("id"));
            System.out.println("name="+rs.getObject("name"));
            System.out.println("password="+rs.getObject("password"));

        }
  rs.close();
        statement.close();
        connection.close();

加载驱动:

提示:Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
说明:“com.mysql.cj.jdbc.Driver” 与驱动不一样

解决方案:

改写驱动driver

 Class.forName("com.mysql.cj.jdbc.Driver");
 Class.forName("com.mysql.jdbc.Driver");

增删改查

  1. 查询全部数据

其中增删改部分与上一部分实例相同,只需传递不同的SQL语句(insert,delete,update)即可实现

  String sql = "select * from student";// sql语句 
  ResultSet rs = s.executeQuery(sql);// 执行查询语句,并把结果集返回给ResultSet
  while (rs.next()) {
    int id = rs.getInt("id");// 可以使用字段名
    String name = rs.getString(2);// 也可以使用字段的顺序
    String pwd = rs.getString(3);
    System.out.printf("%d %s %s \n", id, name, pwd);
  }

使用executeQuery() 执行SQL查询语句,并将查询到的信息存储在ResultSet中
2. 查询特定数据

  String p = "abcdef";
  int id = 10;
  String sql = "select * from student where id = '" + id + "' and password = '" + p + "'";

  // 执行查询语句,并把结果集返回给ResultSet
  ResultSet rs = s.executeQuery(sql);

  if (rs.next())
    System.out.println("账号密码正确");
  else
    System.out.println("账号密码错误");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值