java中级阶段 - 连接数据库(JDBC、Dao)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: JDBC、Dao

1.JDBC基本使用

导读补充

1.1.JDBC是什么?

java DataBase Connectivity (Java语言连接数据库)

1.2.JDBC的本质是什么?

JDBC是sun公司制定的一套接口(interface)

接口都有调用者和实现者。

面向接口调用、面向接口写实现类,这都属于面向接口编程

  • 为什么要面向接口编程?
  • 解耦合:降低程序的耦合度,提高程序的扩展力。
  • 多态机制就是非常典型的:面向抽象编程。(不要面向具体编程)

3.png

1.3.JDBC七步走

package com.Li.JDBCs;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @Description: JDBC七步走
 * @auther:Li Ya Hui
 * @Time:2021年5月20日下午3:41:38
 */
public class Test {
  public static void main(String[] args) throws ClassNotFoundException, SQLException{
    //连库四要素
    String driverName =  "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/class2021change?useUnicode=true&characterEncoding=utf-8";
    String userName = "root";
    String Password = "root";
    String sql_query = "select * from student";
    //1.加载驱动
    Class.forName(driverName);
    //2.指定URL/用户名+密码
    Connection conn = DriverManager.getConnection(url, userName, Password);
    //3.获取链接
    if(!conn.isClosed()) 
    {
      System.out.println("连接成功了");
      //4.创建stmt对象
      Statement stmt = conn.createStatement();
      //5.执行sql语句
      ResultSet rs = stmt.executeQuery(sql_query);
      //6.循环结果集对象 
      while (rs.next()) {
System.out.println(rs.getString("sno")+"\t"+rs.getString("sname")+"\t"+rs.getInt("sage")+"\t"+rs.getString("ssex"));
      }
      //7.关闭连接
      rs.close();
      stmt.close();
      conn.close();
    }
  }
}

2.Dao

把jdbc的七步走 以及增删改查操作封装成自己的类

package com.Li.dao;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Description:  利用JDBC重构获取一个Dao工具
 * @auther:Li Ya Hui
 * @Time:2021年5月20日下午6:40:12
 */
public class Dao {
  //连库四要素
  private String driverName =  "com.mysql.jdbc.Driver";
  private String url = "jdbc:mysql://localhost:3306/class2021change?useUnicode=true&characterEncoding=utf-8";
  private String userName = "root";
  private String Password = "root";
  /**
   * @return 1.获取链接
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  private  Connection getConnection() throws ClassNotFoundException, SQLException {
    //1.加载驱动
    Class.forName(driverName);
    //2.指定URL/用户名+密码
    Connection conn = DriverManager.getConnection(url, userName, Password);
    return conn;
  }
  /**
   * @desc 2.释放连接
   * @param conn
   * @param stmt
   * @param rs
   * @throws SQLException
   */
  private  void releaseConnection(Connection conn, Statement stmt, ResultSet rs) throws SQLException {
    //7.关闭连接
    if (rs!=null) {
      rs.close();
    }
    if (stmt!=null)
    {
      stmt.close();     
    }
    if(conn!=null&!conn.isClosed()) 
    {     
      conn.close();
    }
    System.out.println("releaseConnection");
  }
  //ps:我们对数据库的操作,可以最终归纳为四个动作:增删改查
  /**
   * @desc 3.查询全部
   * @param sql
   * @return
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  public List<Map< String , Object >> executeQueryForList(String sql) throws ClassNotFoundException, SQLException{
    System.out.println("查询全部sql语句"+sql);
    Connection conn = this.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    List<Map<String ,Object>> list = rsToList(rs);
    this.releaseConnection(conn, stmt, rs);
    return list;
  }
  /**
   * //5.查询单条记录
   * @param sql
   * @return
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  public Map<String, Object> executeQueryForMap(String sql) throws ClassNotFoundException, SQLException{
    System.out.println("查询一条信息");
    Connection conn = null ;
    Statement stmt = null;
    ResultSet rs = null;
    List<Map<String, Object>> list;
    try {
      conn = this.getConnection();
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql);
      list = this.rsToList(rs);
      if(!list.isEmpty()) {
        return list.get(0);
      }
    } 
    //释放资源
    finally {
      this.releaseConnection(conn, stmt, rs);
    }
    return null;
  }
  /**
   * @desc 6.查询一共有多少条
   * @param sql
   * @return
   * @throws SQLException
   * @throws ClassNotFoundException
   */
  public int executeQueryForCount(String sql) throws SQLException, ClassNotFoundException 
  {
    System.out.println("查询一共有多少条的sql:"+sql);
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      conn = this.getConnection();
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql);
      if(rs.next()) 
      {
        System.out.println("ss");
        return rs.getInt(1);
      }
    }finally {
      releaseConnection(conn, stmt, rs);
    }
    return 0;
  }
  /**
   * @desc 7.执行添加、删除、修改操作
   * @param sql
   * @return
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  public int  executeUpdate(String sql) throws ClassNotFoundException, SQLException 
  {
    System.out.println("执行添加、修改、删除、等操作的sql"+sql);
    Connection conn = this.getConnection();
    Statement stmt = conn.createStatement();
    //执行sql语句
    int count = stmt.executeUpdate(sql);
    this.releaseConnection(conn, stmt);
    return 0;
  }
  /**
   * @desc 关闭连接
   * @param conn
   * @param stmt
   * @throws SQLException 
   */
  private void releaseConnection(Connection conn, Statement stmt) throws SQLException {
    if (stmt!=null)
    {
      stmt.close();     
    }
    if(conn!=null&!conn.isClosed()) 
    {     
      conn.close();
    }
    System.out.println("releaseConnection");
  }
  /**
   * 4.将rs结果集转变为List 
   * @param rs
   * @return
   * @throws SQLException
   */
  private List<Map<String, Object>> rsToList(ResultSet rs) throws SQLException {
    List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
    System.out.println("表中有:"+rs.getMetaData().getColumnCount()+"列");
    while (rs.next()) //控制循环行
    {
      //创建一个map 收集数据
      Map<String, Object> colsMap = new HashMap<String, Object>();
      //根据
      for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
        switch (rs.getMetaData().getColumnType(i)) {
        case Types.VARCHAR:
          colsMap.put(rs.getMetaData().getColumnName(i), rs.getString(i));
          break;
        case Types.INTEGER:
          colsMap.put(rs.getMetaData().getColumnName(i), rs.getInt(i));
          break;
        case Types.BLOB://二进制  图片类型
          InputStream in = rs.getBinaryStream(i);
          colsMap.put(rs.getMetaData().getColumnName(i), in);
          break;
        default:
          colsMap.put(rs.getMetaData().getColumnName(i), rs.getString(i));
          break;
        }
      }
      rows.add(colsMap);
    }
    return rows;
  }
  public static void main(String[] args) throws Exception{
    Dao dao = new Dao();
        //执行查询表
    System.out.println(dao.executeQueryForList("select * from student"));
    //执行单条记录
    System.out.println(dao.executeQueryForMap("select * from student where sno='s001' "));
    //执行查询条数
    System.out.println(dao.executeQueryForCount("select count(*) from student  "));
    //执行修改
    System.out.println(dao.executeUpdate("update student set sname='李亚辉' where sname='张三'"));
  }
}
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
4月前
|
负载均衡 算法 关系型数据库
大数据大厂之MySQL数据库课程设计:揭秘MySQL集群架构负载均衡核心算法:从理论到Java代码实战,让你的数据库性能飙升!
本文聚焦 MySQL 集群架构中的负载均衡算法,阐述其重要性。详细介绍轮询、加权轮询、最少连接、加权最少连接、随机、源地址哈希等常用算法,分析各自优缺点及适用场景。并提供 Java 语言代码实现示例,助力直观理解。文章结构清晰,语言通俗易懂,对理解和应用负载均衡算法具有实用价值和参考价值。
大数据大厂之MySQL数据库课程设计:揭秘MySQL集群架构负载均衡核心算法:从理论到Java代码实战,让你的数据库性能飙升!
|
20天前
|
SQL Java 关系型数据库
Java连接MySQL数据库环境设置指南
请注意,在实际部署时应该避免将敏感信息(如用户名和密码)硬编码在源码文件里面;应该使用配置文件或者环境变量等更为安全可靠地方式管理这些信息。此外,在处理大量数据时考虑使用PreparedStatement而不是Statement可以提高性能并防止SQL注入攻击;同时也要注意正确处理异常情况,并且确保所有打开过得资源都被正确关闭释放掉以防止内存泄漏等问题发生。
64 13
|
22天前
|
SQL 关系型数据库 MySQL
MySQL数据库连接过多(Too many connections)错误处理策略
综上所述,“Too many connections”错误处理策略涉及从具体参数配置到代码层面再到系统与架构设计全方位考量与改进。每项措施都需根据具体环境进行定制化调整,并且在执行任何变更前建议先行测试评估可能带来影响。
378 11
|
5月前
|
NoSQL Java API
在Java环境下如何进行Redis数据库的操作
总的来说,使用Jedis在Java环境下进行Redis数据库的操作,是一种简单而高效的方法。只需要几行代码,就可以实现复杂的数据操作。同时,Jedis的API设计得非常直观,即使是初学者,也可以快速上手。
275 94
|
2月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
272 0
|
5月前
|
SQL 数据库连接 数据库
在C++的QT框架中实现SQLite数据库的连接与操作
以上就是在C++的QT框架中实现SQLite数据库的连接与操作的基本步骤。这些步骤包括创建数据库连接、执行SQL命令、处理查询结果和关闭数据库连接。在实际使用中,你可能需要根据具体的需求来修改这些代码。
300 14
|
5月前
|
Java 关系型数据库 MySQL
Java汽车租赁系统源码(含数据库脚本)
Java汽车租赁系统源码(含数据库脚本)
101 4
|
11月前
|
Java 关系型数据库 MySQL
mysql5.7 jdbc驱动
遵循上述步骤,即可在Java项目中高效地集成MySQL 5.7 JDBC驱动,实现数据库的访问与管理。
2168 1