JDBC使用List和Map鍵值封裝多表查詢結果


查詢結果的處理

Java.sql.ResultSet接口是jdbcAPI中唯一用來封裝查詢結果記錄行的組件。

ResultSet接口唯一創建方式是通過執行SQL查詢返回創建此對象

 

遍歷結果集中數據

  1. true next()方法
  2. getXXX(int index);getXXX(String colum)

 

while(結果集對象.next()){

變量 = 結果集對象.getXX(1);

變量1 = 結果集對象.getXX(2);

變量2 = 結果集對象.getXX(age);

變量3 = 結果集對象.getXX(birth);

變量4 = 結果集對象.getXX(sex);

empList.add(emp;)//Emp對象添加到List集合中存儲

}

 

封裝結果集中數據行。

每次循環獲取結果集當前行封裝Java對象后應將其存儲在集合或數組中。

使用Map代替自定義實體類封裝查詢結果數據

優點:減少大量自定義Java類的定義

缺點:通常認為不是好的設計,訪問沒有java類方便

 

使用數據庫連接池

01 C3P0連接池

02 DBCP連接池

03 Proxool連接池

04 BoneCP連接池

05 Druid(阿里巴巴德魯伊)連接池

package com.xzit.dao;

import com.xzit.db.util.DataSourceManager;
import com.xzit.pojo.Department;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
* 數據訪問處理組件,實現對dep_tab 部門表進行增,刪,改,查操作
* */
public class DepartmentDao {

    /*
    * 添加新部門的方法
    * @param dep 新添加的部門
    * */
    public int addDepartment(Department dep){
        int res = 0;
        String sql="insert into dep_table " +
                "(id,name,createtime,descs) values (?,?,?,?)";  //sql插入語句
        Connection conn = DataSourceManager.getConnection();    //獲取數據庫連接
        PreparedStatement ps = null;    //獲取PreparedStatement接口對象

        try {
            ps = conn.prepareStatement(sql);    //獲取PreparedStatement對象
            /* 設置替換sql語句中的參數占位符? */
            ps.setString(1,"NO008");
            ps.setString(2,dep.getName());
            ps.setDate(3,new java.sql.Date(dep.getCreateDate().getTime()));
            ps.setString(4,dep.getDescs());
            res = ps.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {  //關閉數據庫連接,釋放資源
            DataSourceManager.close(ps);
            DataSourceManager.close(conn);
        }
        return res;
    }

    /**
     * 修改選定的部門對象
     * @param dep 欲修改的部門
     * @return
     */
    public int modifyDepartment(Department dep){
        int res = 0;
        String sql = "update dep_table set name = ?,createtime=?,descs=? "
                + "where id=?";
        Connection conn = DataSourceManager.getConnection();    //獲取數據庫連接
        PreparedStatement ps = null;    //獲取PreparedStatement接口對象

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,dep.getName());
            ps.setDate(2,new java.sql.Date(dep.getCreateDate().getTime()));
            ps.setString(3,dep.getDescs());
            ps.setString(4,dep.getId());
            res = ps.executeUpdate();
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            DataSourceManager.close(ps);
            DataSourceManager.close(conn);
        }
        return res;
    }

    /**
     * 刪除部門對象
     * @param id 刪除部門的id
     * @return
     */
    public int deleteDepartmentById(String id){
        int res = 0;
        String sql = "delete from dep_table where id = '"+id+"'";
        Connection conn = DataSourceManager.getConnection();    //獲取連接
        PreparedStatement ps = null;    //獲取PreparedStatement接口對象

        try {
            ps = conn.prepareStatement(sql);
            //執行刪除操作
            res = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {  //關閉數據庫連接
            DataSourceManager.close(ps);
            DataSourceManager.close(conn);
        }
        return res;
    }

    /**
     * 查詢獲取所有部門信息列表
     * @return List<Department> 所有部門列表
     */
    public List<Department> queryDepartmentList(){
        List<Department> depList = new ArrayList<Department>();
        String sql = "select ID depid,NAME depname," +
                "CREATETIME createdate,DESCS dec from dep_table";
        Connection conn = DataSourceManager.getConnection();    //獲取連接
        PreparedStatement ps = null;    //獲取PreparedStatement接口對象
        ResultSet set = null;
        try {
            ps = conn.prepareStatement(sql);
            set = ps.executeQuery();    //查詢返回ResultSet結果集對象
            /* 處理結果集,封裝結果集中行為java對象 */
            while(set.next()){
                Department dep = new Department();//每一行創建一個Department對象
                String id = set.getString(1);   //獲取第1列id列值
                dep.setId(id);
                dep.setName(set.getString("depname"));
                dep.setCreateDate(set.getDate("createdate"));
                dep.setDescs(set.getString(4));
                depList.add(dep);//將dep對象添加到List集合中
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.close(set);
            DataSourceManager.close(ps);
            DataSourceManager.close(conn);
        }
        return depList; //返回封裝Department List集合
    }

    /**
     * 查詢員工年齡大於給定參數的信息
     * @param age 年齡
     * @return
     */
    public List<Map<String,Object>> queryEmpByArgs(int age){
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        String sql = "select d.NAME dname,e.NAME ename,e.address,e.age\n"
                   + "from dep_table d INNER JOIN emp_tab e\n"
                   + "on d.id = e.dep_id where e.age > "+age+"";
        Connection conn = DataSourceManager.getConnection();    //獲取連接
        PreparedStatement ps = null;    //獲取PreparedStatement接口對象
        ResultSet set = null;
        try {
            ps = conn.prepareStatement(sql);
            set = ps.executeQuery();    //查詢返回ResultSet結果集對象
            /* 處理結果集,封裝結果集中行為java對象 */
            while(set.next()){
                Map<String,Object> map = new HashMap<String,Object>();  //每行記錄封裝為Map對象
                map.put("dname",set.getString("dname"));
                map.put("ename",set.getString("ename"));
                map.put("address",set.getString("address"));
                map.put("age",set.getInt("age"));
                list.add(map);//將Map對象添加到List集合中
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.close(set);
            DataSourceManager.close(ps);
            DataSourceManager.close(conn);
        }
        return list;//返回封裝Map對象的List接口對象
    }
}
package com.xzit.test;

import com.xzit.dao.DepartmentDao;
import com.xzit.pojo.Department;

import java.util.List;

public class BaseQueryTest {
    public static void main(String[] args) {
        List<Department> deps = new DepartmentDao().queryDepartmentList();

        System.out.println("ID編號\t部門名稱\t成立日期\t部門描述");

        for (Department dep:deps){
            System.out.println(dep.getId()+"\t"+dep.getName()
                    + "\t"+dep.getCreateDate()+"\t"
                    + (dep.getDescs()==null?"":dep.getDescs()));
        }
    }
}
package com.xzit.test;

import com.xzit.dao.DepartmentDao;

import java.util.List;
import java.util.Map;

public class TestMap {
    public static void main(String[] args) {
        List<Map<String,Object>> list = new DepartmentDao().queryEmpByArgs(27);

        for (Map<String,Object> map:list){

            System.out.println(map.get("dname")+"\t"+map.get("ename")
            +"\t"+map.get("address")+"\t"+map.get("age"));
        }
    }
}
package com.xzit.db.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;

public class DataSourceForPool {

    private static ComboPooledDataSource c3p0;

    /**
     * 創建ComboPooledDataSource數據源
     */
    private static void createComboPooledDataSource(){

        if(c3p0 == null){
            c3p0 = new ComboPooledDataSource();
            /* 數據源相關屬性 */
            try {
                c3p0.setDriverClass(Env.JDBC_DRIVER);
                c3p0.setUser(Env.JDBC_USER);
                c3p0.setPassword(Env.JDBC_PASSWORD);
                c3p0.setJdbcUrl(Env.JDBC_URL);
                c3p0.setCheckoutTimeout(3000);
                c3p0.setDataSourceName("c3p0DataSource");
                c3p0.setMaxPoolSize(30);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>2021_10_13_jdbcapp</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>2021_10_13_jdbcapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8 -->
    <dependency>
      <groupId>com.oracle.database.jdbc</groupId>
      <artifactId>ojdbc8</artifactId>
      <version>12.2.0.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.5</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM