JDBC使用步骤

109 篇文章 0 订阅

多情只有春庭月,犹为离人照落花。——张泌《寄人》

  • 准备数据库驱动包(比如: MySQL数据库的驱动包

  • 加载JDBC驱动程序

      Class.forName("com.mysql.jdbc.Driver");
    
  • 建立数据库连接

       Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/memo?user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
    
      MySQL数据连接的URL参数格式如下:
    
      jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
    
  • 创建操作命令(statement)

      Statement statement = connection.createStatement();
    
  • 执行SQL语句

      ResultSet resultSet= statement.executeQuery(
              "select id,group_id,title,content,is_protected, backgroup,is_remind,remind_time,created_time,modify_time from memo_info");
    
  • 处理结果集

       while (resultSet.next()) {
          int id = resultSet.getInt("id");
          String title = resultSet.getString("title");
          String content = resultSet.getString("content");
          Date createTime = resultSet.getDate("created_time");
          System.out.println(String.format("Memo: id=%d, title=%s, content=%s, createTime=%s", id, title, content, createTime.toString()));
      }
    
  • 释放资源(关闭结果集,命令,连接)

      //关闭结果集
      if (resultSet != null) {
          try {
              resultSet.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
      //关闭命令
      if (statement != null) {
          try {
              statement.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
      //关闭连接命令
      if (connection != null) {
          try {
              connection.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值