JDBC

概念

Java DataBase Connectivity Java 数据库连接。是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。

JDBC 连接数据库的步骤

  1. 导入驱动jar包
  2. 注册驱动
  3. 定义sql
  4. 获取数据库连接对象 Connection
  5. 获取执行sql语句的对象 Statement
  6. 执行sql,接受返回结果
  7. 处理结果
  8. 关闭资源
注意: 按照此步骤连接数据库会出现sql注入问题,解决此问题的方法见下方。
示例代码:

@Test
public void test(){
    Connection conn = null;
    Statement stmt = null;
    try {
        //1.导入驱动jar包
        //2.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        //3.获取数据库连接对象  ?characterEncoding=utf-8  确保sql语句执行后不会出现乱码
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/news?characterEncoding=utf-8", "root", "root");
        //4.定义sql语句
        String sql = "update student set name ='笑哈哈' where id = 5";
        //5.获取执行sql的对象 Statement
        stmt = conn.createStatement();
        //6.执行sql
        int i = stmt.executeUpdate(sql);
        //7.处理结果
        System.out.println(i);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        //8.释放资源
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

使用PreparedStatement解决sql注入问题

步骤:
  1. 导入驱动jar包
  2. 注册驱动
  3. 获取数据库连接对象 Connection
  4. 定义sql
    * 注意:sql的参数使用?作为占位符。 如:select * from user where username = ? and password = ?;
  5. 获取执行sql语句的对象 PreparedStatement Connection.prepareStatement(String sql)
  6. 给?赋值:
    * 方法: setXxx(参数1,参数2)
    * 参数1:?的位置编号 从1 开始
    * 参数2:?的值
  7. 执行sql,接受返回结果,不需要传递sql语句
  8. 处理结果
  9. 释放资源
示例代码:

 @Test
public void test(){
    Connection conn = null;
    PreparedStatement pstmt1 =null;
    PreparedStatement pstmt2 = null;

    try {
        //1.获取连接
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/news?characterEncoding=utf-8", "root", "root");
        //2.定义sql
        String sql1 = "update user set balance = balance - ? where id = ?";
        String sql2 = "update user set balance = balance + ? where id = ?";
        //3.获取执行sql对象
        pstmt1 = conn.prepareStatement(sql1);
        pstmt2 = conn.prepareStatement(sql2);
        //4.设置参数
        pstmt1.setDouble(1,500);
        pstmt1.setInt(2,1);

        pstmt2.setDouble(1,500);
        pstmt2.setInt(2,2);

        //5.执行sql
        pstmt1.executeUpdate();
        pstmt2.executeUpdate();
        
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //7.释放资源
        if ( pstmt2 != null){
            try {
                pstmt2.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt1 != null){
            try {
                pstmt1.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

自定义工具类 JDBCUtils

示例代码:

public class JDBCUtils {

private static String url;
private static String user;
private static String password;
private static String driver;

  /*
  文件的读取,只需要读取一次即可,使用静态代码块
   */
static {
    //读取资源文件,获取值。

      try {
          //1.创建Properties集合类
          Properties pro = new Properties();

          //获取src路径下的文件的方式  ---->ClassLoader 类加载器
          ClassLoader classLoader = JDBCUtils.class.getClassLoader();
          URL resource = classLoader.getResource("jdbc.properties");
          String path = resource.getPath();
          // System.out.println(path);

          //2.加载文件
            pro.load(new FileReader(path));
          //3. 获取数据,赋值
          url = pro.getProperty("url");
          user = pro.getProperty("user");
          password = pro.getProperty("password");
          driver = pro.getProperty("driver");

          //4.注册驱动
          Class.forName(driver);

      } catch (IOException e) {
          e.printStackTrace();
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
  }
  
/*
获取连接,返回连接对象
 */
public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(url,user,password);
}

/*
释放资源
 */
public static void Close(Statement stmt,Connection conn){
    if (stmt != null){
        try {
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (conn != null){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
/*
释放资源重载方法,加上ResultSet
 */
    public static void Close(ResultSet rs , Statement stmt, Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

练习:

问题描述:用户通过键盘录入用户名和密码,判断用户是否登录成功(使用上述的自定义工具类)。
解决方式:

  public static void main(String[] args)  {

    //1.键盘录入,接收用户名和密码
    Scanner sc  = new Scanner(System.in);
    System.out.println("请输入用户名:");
    String username = sc.nextLine();
    System.out.println("请输入密码:");
    String password = sc.nextLine();
    
    //2.调用方法
    boolean flag = new JdbcDemo().Login0(username, password);

    //3.判断结果,输出结果
    if (flag){
        System.out.println("登录成功");
    }else{
        System.out.println("用户名或密码错误,请重新再试");
    }
}

/*
登录方法  该方法存在bug
          输入错误的用户名,输入用户密码为: a' or 'a' = 'a  会登录成功
 */
public boolean Login(String username, String password)  {
    if (username == null || password == null){
        return false;
    }
    //连接数据库判断是否登录成功

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        //1.获取连接
        conn = JDBCUtils.getConnection();
        String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
        //3.获取执行sql的对象
        stmt = conn.createStatement();
        //4.执行查询
        rs = stmt.executeQuery(sql);
        //5.判断
        return  rs.next();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JDBCUtils.Close(rs,stmt,conn);
    }

  return false;
}

/*
登录方法,使用PreparedStatement ,修改上述bug
 */
public boolean Login0(String username, String password)  {
    if (username == null || password == null){
        return false;
    }
    //连接数据库判断是否登录成功

    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        //1.获取连接
        conn = JDBCUtils.getConnection();
        String sql = "select * from user where username = ? and password = ?";
        //3.获取执行sql的对象
        pstmt = conn.prepareStatement(sql);
        //给?赋值
        pstmt.setString(1,username);
        pstmt.setString(2,password);

        //4.执行查询
         rs = pstmt.executeQuery();
        //5.判断
        return  rs.next();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JDBCUtils.Close(rs,pstmt,conn);
    }
  return false;
}

JDBC 数据库连接池

1.概念:

是一个容器(集合),存放数据库连接的容器。
当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。

2. 好处:

  1. 节约资源 。
  2. 用户访问高效 。

3. 实现:

3.1 标准接口:DataSource javax.sql包下的
   方法:
    获取连接:getConnection()
    归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么当调用Connection.close()方法时,不会再关闭连接,而是归还连接。
3.2 一般我们不去实现它,由数据库厂商来实现。
  1. C3P0:数据库连接池技术。
  2. Druid:数据库连接池实现技术,由阿里巴巴提供的。

C3P0:数据库连接池技术 步骤:

  1. 导入jar包 (两个) c3p0-0.9.5.2.jar   mchange-commons-java-0.2.12.jar
注意 不要忘记导入数据库驱动jar包。
2. 定义配置文件:
  名称: c3p0.properties 或者 c3p0-config.xml
  路径:直接将文件放在src目录下即可。
3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
4. 获取连接: getConnection
c3p0-config.xml配置文件:

        <c3p0-config>
        <!-- 使用默认的配置读取连接池对象 -->
        <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/online_exam_system?characterEncoding=utf-8</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!-- 连接池参数 -->
        <!-- 初始化连接数量 -->
        <property name="initialPoolSize">5</property>
        <!-- 最大连接数量,可以根据自己的需要调整 -->
        <property name="maxPoolSize">10</property>
        <!-- 超时时间的毫秒数 -->
        <property name="checkoutTimeout">3000</property>
        </default-config>

        <named-config name="otherc3p0"> 
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/online_exam_system</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <!-- 连接池参数 -->
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">8</property>
        <property name="checkoutTimeout">1000</property>
        </named-config>
        </c3p0-config>

示例代码:

//使用默认配置获取DataSource
@Test
public void test1() throws SQLException {
    //1.获取DataSource,使用默认配置
    DataSource ds = new ComboPooledDataSource();

    //2.获取连接(验证最大连接数量)
    for (int i = 1 ;i <= 10 ; i++){
        Connection conn = ds.getConnection();
        System.out.println(i + ":" + conn );
    }
}

//使用指定名称配置获取DataSource
 @Test
public void test2() throws SQLException {
    //1获取DataSource,使用指定名称配置
    DataSource ds = new ComboPooledDataSource("otherc3p0");

    //2.获取连接(验证最大连接数量),因为xml文件中的设置的最大连接数量是8,此时会报异常
    for (int i = 1 ;i <= 10 ; i++){
        Connection conn = ds.getConnection();
        System.out.println(i + ":" + conn );
    }
}

Druid:数据库连接池实现技术

1. 步骤:

  1. 导入jar包 druid-1.0.9.jar

  2. 定义配置文件:
        是properties形式的。
        可以叫任意名称,可以放在任意目录下。

  3. 加载配置文件。Properties。

  4. 获取数据库连接池对象:通过工厂类来获取 DruidDataSourceFactory

  5. 获取连接:getConnection
    示例代码:

     @Test
     public void test() throws Exception {
         //1.导入jar包
         //2.定义配置文件
         //3.加载配置文件
         Properties pro = new Properties();
         InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
         pro.load(is);
         //4.获取连接池对象
         DataSource ds = DruidDataSourceFactory.createDataSource(pro);
    
         //5.获取连接
         Connection conn = ds.getConnection();
         System.out.println(conn);
     }
    

2. 自定义工具类

  1. 定义一个类 JDBCUtils
  2. 提供静态代码块加载配置文件,初始化连接池对象
  3. 提供方法
    1. 获取连接方法:通过数据库连接池获取连接
    2. 释放资源
    3. 获取连接池的方法

示例代码:

public class JDBCUtils {
    //1.定义成员变量:DataSource
    private static DataSource ds ;

    static {
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
    获取连接
    */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /*
    释放资源
    */
    public static void close(Statement stmt,Connection conn) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /*
    释放资源的重载方法
    */
    public static void close(ResultSet rs,Statement stmt,Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /*
    获取连接池的方法
    */
    public static DataSource getDataSource(){
        return ds;
    }
}

Spring JDBC

Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发。

步骤:

  1. 导入jar包
  2. 创建JdbcTemplate对象。依赖于数据源DataSource
    JdbcTemplate template = new JdbcTemplate(ds);
  3. 调用JdbcTemplate的方法来完成CRUD的操作
      update():执行DML语句。增、删、改语句
      queryForMap():查询结果将结果集封装为map集合,列名作为key,值作为value, 将这条记录封装为一个map集合.
    注意:这个方法查询的结果集长度只能是1
      queryForList():查询结果将结果集封装为list集合
    注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
      query():查询结果,将结果封装为JavaBean对象。
    query的参数:RowMapper 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
        new BeanPropertyRowMapper<类型>(类型.class)
      queryForObject():查询结果,将结果封装为对象,一般用于聚合函数的查询。

练习:
问题描述:

  1. 修改1号数据的 salary 为 666
  2. 添加一条记录
  3. 删除刚才添加的记录
  4. 查询id为1的记录,将其封装为Map集合
  5. 查询所有记录,将其封装为List
  6. 查询所有记录,将其封装为Emp对象的List集合
  7. 查询总记录数.

示例代码:

private  JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//修改1号数据的 salary为666
@Test
public void test1(){
    String sql = "update manager set salary = 666 where id = ?";
    int count = template.update(sql, 1);
    System.out.println(count);
    if (count > 0){
        System.out.println("更新成功");
    }else{
        System.out.println("更新失败");
    }
}

//添加一条记录
@Test
public void test2(){

  String sql = "insert into manager values(null,?,?,?,?) ";
    int count = template.update(sql, "manager7", "m7", "super", 1666);
    if (count > 0){
        System.out.println("更新成功");
    }else{
        System.out.println("更新失败");
    }
}

//删除刚才添加的记录
@Test
public void test3(){
 String sql = "delete from manager where id = ?";
    int count = template.update(sql, 7);
    if (count > 0){
        System.out.println("更新成功");
    }else{
        System.out.println("更新失败");
    }
}

/*
查询id为 1 的记录,将其封装成Map集合
注意:queryForMap()查询的结果集长度只能为1
 */
@Test
public void test4(){
String  sql = "select * from  manager where id = ?";
    Map<String, Object> map = template.queryForMap(sql, 1);
    System.out.println(map);
}

//查询所有记录,将其封装成List集合
@Test
public void test5(){
    String sql = "select * from manager";
    List<Map<String, Object>> maps = template.queryForList(sql);
    Iterator<Map<String, Object>> iterator = maps.iterator();
    while (iterator.hasNext()){
        System.out.println(iterator.next());
    }
}

//查询所有记录,将其封装为Manager对象的List集合
@Test
public void test6(){
    String sql = "select * from manager";
    List<Manager> list = template.query(sql, new RowMapper<Manager>() {
        @Override
        public Manager mapRow(ResultSet rs, int i) throws SQLException {
            Manager manager = new Manager();
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String password = rs.getString("password");
            String authority = rs.getString("authority");
            double salary = rs.getDouble("salary");

            manager.setId(id);
            manager.setName(name);
            manager.setPassword(password);
            manager.setAuthority(authority);
            manager.setSalary(salary);

            return manager;
        }
    });
    for (Manager manager : list){
        System.out.println(manager);
    }
}

//查询所有记录,将其封装为Manager对象的List集合的改进
@Test
public void test7(){
    String sql = "select * from manager";
    List<Manager> list = template.query(sql, new BeanPropertyRowMapper<Manager>(Manager.class));
    for (Manager manager : list){
        System.out.println(manager);
    }
}

//查询总记录数
@Test
public void test8(){
 String sql = "select count(id) from manager";
    Long total = template.queryForObject(sql, Long.class);
    System.out.println(total);
}
原文地址:https://www.cnblogs.com/gujun1998/p/11282863.html