主頁 > 後端開發 > Java讀取資料庫表(二)

Java讀取資料庫表(二)

2023-05-05 08:18:42 後端開發

Java讀取資料庫表(二)

img1

application.properties

db.driver.name=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/easycrud?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
db.username=root
db.password=xpx24167830

#是否忽略表前綴
ignore.table.prefix=true

#引數bean后綴
suffix.bean.param=Query

輔助閱讀

組態檔中部分資訊被讀取到之前檔案說到的Constants.java中以常量的形式存盤,BuildTable.java中會用到,常量命名和上面類似,

StringUtils.java

package com.easycrud.utils;

/**
 * @BelongsProject: EasyCrud
 * @BelongsPackage: com.easycrud.utils
 * @Author: xpx
 * @Email: [email protected]
 * @CreateTime: 2023-05-03  13:30
 * @Description: 字串大小寫轉換工具類
 * @Version: 1.0
 */

public class StringUtils {
    /**
     * 首字母轉大寫
     * @param field
     * @return
     */
    public static String uperCaseFirstLetter(String field) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(field)) {
            return field;
        }
        return field.substring(0, 1).toUpperCase() + field.substring(1);
    }

    /**
     * 首字母轉小寫
     * @param field
     * @return
     */
    public static String lowerCaseFirstLetter(String field) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(field)) {
            return field;
        }
        return field.substring(0, 1).toLowerCase() + field.substring(1);
    }

    /**
     * 測驗
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(lowerCaseFirstLetter("Abcdef"));
        System.out.println(uperCaseFirstLetter("abcdef"));
    }
}

輔助閱讀

org.apache.commons.lang3.StringUtils.isEmpty()

只能判斷String型別是否為空(org.springframework.util包下的Empty可判斷其他型別),原始碼如下

public static boolean isEmpty(final CharSequence cs) {
	return cs == null || cs.length() == 0;
}

xx.toUpperCase()

字母轉大寫

xx.toLowerCase()

字母轉小寫

xx.substring()

回傳字串的子字串

索引從0開始
public String substring(int beginIndex)	//起始索引,閉
public String substring(int beginIndex, int endIndex)	//起始索引到結束索引,左閉右開

BuildTable.java完整代碼

package com.easycrud.builder;

import com.easycrud.bean.Constants;
import com.easycrud.bean.FieldInfo;
import com.easycrud.bean.TableInfo;
import com.easycrud.utils.JsonUtils;
import com.easycrud.utils.PropertiesUtils;
import com.easycrud.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: EasyCrud
 * @BelongsPackage: com.easycrud.builder
 * @Author: xpx
 * @Email: [email protected]
 * @CreateTime: 2023-05-02  18:02
 * @Description: 讀Table
 * @Version: 1.0
 */

public class BuildTable {

    private static final Logger logger = LoggerFactory.getLogger(BuildTable.class);
    private static Connection conn = null;

    /**
     * 查表資訊,表名,表注釋等
     */
    private static String SQL_SHOW_TABLE_STATUS = "show table status";

    /**
     * 將表結構當作表讀出欄位的資訊,如欄位名(field),型別(type),自增(extra)...
     */
    private static String SQL_SHOW_TABLE_FIELDS = "show full fields from %s";

    /**
     * 檢索索引
     */
    private static String SQL_SHOW_TABLE_INDEX = "show index from %s";

    /**
     * 讀配置,連接資料庫
     */
    static {
        String driverName = PropertiesUtils.getString("db.driver.name");
        String url = PropertiesUtils.getString("db.url");
        String user = PropertiesUtils.getString("db.username");
        String password = PropertiesUtils.getString("db.password");

        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url,user,password);
        } catch (Exception e) {
            logger.error("資料庫連接失敗",e);
        }
    }

    /**
     * 讀取表
     */
    public static List<TableInfo> getTables() {
        PreparedStatement ps = null;
        ResultSet tableResult = null;

        List<TableInfo> tableInfoList = new ArrayList();
        try{
            ps = conn.prepareStatement(SQL_SHOW_TABLE_STATUS);
            tableResult = ps.executeQuery();
            while(tableResult.next()) {
                String tableName = tableResult.getString("name");
                String comment = tableResult.getString("comment");
                //logger.info("tableName:{},comment:{}",tableName,comment);

                String beanName = tableName;
                /**
                 * 去xx_前綴
                 */
                if (Constants.IGNORE_TABLE_PREFIX) {
                    beanName = tableName.substring(beanName.indexOf("_")+1);
                }
                beanName = processFiled(beanName,true);

//                logger.info("bean:{}",beanName);

                TableInfo tableInfo = new TableInfo();
                tableInfo.setTableName(tableName);
                tableInfo.setBeanName(beanName);
                tableInfo.setComment(comment);
                tableInfo.setBeanParamName(beanName + Constants.SUFFIX_BEAN_PARAM);

                /**
                 * 讀欄位資訊
                 */
                readFieldInfo(tableInfo);

                /**
                 * 讀索引
                 */
                getKeyIndexInfo(tableInfo);

//                logger.info("tableInfo:{}",JsonUtils.convertObj2Json(tableInfo));

                tableInfoList.add(tableInfo);

//                logger.info("表名:{},備注:{},JavaBean:{},JavaParamBean:{}",tableInfo.getTableName(),tableInfo.getComment(),tableInfo.getBeanName(),tableInfo.getBeanParamName());
            }
            logger.info("tableInfoList:{}",JsonUtils.convertObj2Json(tableInfoList));
        }catch (Exception e){
            logger.error("讀取表失敗",e);
        }finally {
            if (tableResult != null) {
                try {
                    tableResult.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return tableInfoList;
    }

    /**
     * 將表結構當作表讀出欄位的資訊,如欄位名(field),型別(type),自增(extra)...
     * @param tableInfo
     * @return
     */
    private static void readFieldInfo(TableInfo tableInfo) {
        PreparedStatement ps = null;
        ResultSet fieldResult = null;

        List<FieldInfo> fieldInfoList = new ArrayList();
        try{
            ps = conn.prepareStatement(String.format(SQL_SHOW_TABLE_FIELDS,tableInfo.getTableName()));
            fieldResult = ps.executeQuery();
            while(fieldResult.next()) {
                String field = fieldResult.getString("field");
                String type = fieldResult.getString("type");
                String extra = fieldResult.getString("extra");
                String comment = fieldResult.getString("comment");

                /**
                 * 型別例如varchar(50)我們只需要得到varchar
                 */
                if (type.indexOf("(") > 0) {
                    type = type.substring(0, type.indexOf("("));
                }
                /**
                 * 將aa_bb變為aaBb
                 */
                String propertyName = processFiled(field, false);

//                logger.info("f:{},p:{},t:{},e:{},c:{},",field,propertyName,type,extra,comment);

                FieldInfo fieldInfo = new FieldInfo();
                fieldInfoList.add(fieldInfo);

                fieldInfo.setFieldName(field);
                fieldInfo.setComment(comment);
                fieldInfo.setSqlType(type);
                fieldInfo.setAutoIncrement("auto_increment".equals(extra) ? true : false);
                fieldInfo.setPropertyName(propertyName);
                fieldInfo.setJavaType(processJavaType(type));

//                logger.info("JavaType:{}",fieldInfo.getJavaType());

                if (ArrayUtils.contains(Constants.SQL_DATE_TIME_TYPES, type)) {
                    tableInfo.setHaveDataTime(true);
                }else {
                    tableInfo.setHaveDataTime(false);
                }
                if (ArrayUtils.contains(Constants.SQL_DATE_TYPES, type)) {
                    tableInfo.setHaveData(true);
                }else {
                    tableInfo.setHaveData(false);
                }
                if (ArrayUtils.contains(Constants.SQL_DECIMAL_TYPE, type)) {
                    tableInfo.setHaveBigDecimal(true);
                }else {
                    tableInfo.setHaveBigDecimal(false);
                }
            }
            tableInfo.setFieldList(fieldInfoList);
        }catch (Exception e){
            logger.error("讀取表失敗",e);
        }finally {
            if (fieldResult != null) {
                try {
                    fieldResult.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 檢索唯一索引
     * @param tableInfo
     * @return
     */
    private static List<FieldInfo> getKeyIndexInfo(TableInfo tableInfo) {
        PreparedStatement ps = null;
        ResultSet fieldResult = null;

        List<FieldInfo> fieldInfoList = new ArrayList();
        try{
            /**
             * 快取Map
             */
            Map<String,FieldInfo> tempMap = new HashMap();
            /**
             * 遍歷表中欄位
             */
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                tempMap.put(fieldInfo.getFieldName(),fieldInfo);
            }

            ps = conn.prepareStatement(String.format(SQL_SHOW_TABLE_INDEX,tableInfo.getTableName()));
            fieldResult = ps.executeQuery();
            while(fieldResult.next()) {
                String keyName = fieldResult.getString("key_name");
                Integer nonUnique = fieldResult.getInt("non_unique");
                String columnName = fieldResult.getString("column_name");

                /**
                 * 0是唯一索引,1不唯一
                 */
                if (nonUnique == 1) {
                    continue;
                }

                List<FieldInfo> keyFieldList = tableInfo.getKeyIndexMap().get(keyName);

                if (null == keyFieldList) {
                    keyFieldList = new ArrayList();
                    tableInfo.getKeyIndexMap().put(keyName,keyFieldList);
                }

                keyFieldList.add(tempMap.get(columnName));
            }
        }catch (Exception e){
            logger.error("讀取索引失敗",e);
        }finally {
            if (fieldResult != null) {
                try {
                    fieldResult.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return fieldInfoList;
    }

    /**
     * aa_bb__cc==>AaBbCc || aa_bb_cc==>aaBbCc
     * @param field
     * @param uperCaseFirstLetter,首字母是否大寫
     * @return
     */
    private static String processFiled(String field,Boolean uperCaseFirstLetter) {
        StringBuffer sb = new StringBuffer();
        String[] fields=field.split("_");
        sb.append(uperCaseFirstLetter ? StringUtils.uperCaseFirstLetter(fields[0]):fields[0]);
        for (int i = 1,len = fields.length; i < len; i++){
            sb.append(StringUtils.uperCaseFirstLetter(fields[i]));
        }
        return sb.toString();
    }

    /**
     * 為資料庫欄位型別匹配對應Java屬性型別
     * @param type
     * @return
     */
    private static String processJavaType(String type) {
        if (ArrayUtils.contains(Constants.SQL_INTEGER_TYPE,type)) {
            return "Integer";
        }else if (ArrayUtils.contains(Constants.SQL_LONG_TYPE,type)) {
            return "Long";
        }else if (ArrayUtils.contains(Constants.SQL_STRING_TYPE,type)) {
            return "String";
        }else if (ArrayUtils.contains(Constants.SQL_DATE_TIME_TYPES,type) || ArrayUtils.contains(Constants.SQL_DATE_TYPES,type)) {
            return "Date";
        }else if (ArrayUtils.contains(Constants.SQL_DECIMAL_TYPE,type)) {
            return "BigDecimal";
        }else {
            throw new RuntimeException("無法識別的型別:"+type);
        }
    }
}

輔助閱讀

去表名前綴,如tb_test-->test

beanName = tableName.substring(beanName.indexOf("_")+1);

indexOf("_")定位第一次出現下劃線的索引位置,substring截取后面的字串,

processFiled(String,Boolean)

自定義方法,用于將表名或欄位名轉換為Java中的類名或屬性名,如aa_bb__cc-->AaBbCc || aa_bb_cc-->aaBbCc

processFiled(String,Boolean)中的String[] fields=field.split("_")

xx.split("_")是將xx字串按照下劃線進行分割,

processFiled(String,Boolean)中的append()

StringBuffer類包含append()方法,相當于“+”,將指定的字串追加到此字符序列,

processJavaType(String)

自定義方法,用于做資料庫欄位型別與Java屬性型別之間的匹配,

processJavaType(String)中的ArrayUtils.contains(A,B)

判斷B是否在A中出現過,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/551607.html

標籤:其他

上一篇:Spring原始碼:Bean生命周期(三)

下一篇:返回列表

標籤雲
其他(158400) Python(38117) JavaScript(25399) Java(18012) C(15221) 區塊鏈(8261) C#(7972) AI(7469) 爪哇(7425) MySQL(7157) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5871) 数组(5741) R(5409) Linux(5334) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4565) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2432) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1964) Web開發(1951) HtmlCss(1931) python-3.x(1918) 弹簧靴(1913) C++(1912) xml(1889) PostgreSQL(1874) .NETCore(1857) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Java讀取資料庫表(二)

    Java讀取資料庫表(二) application.properties db.driver.name=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/easycrud?useUnicode=true&characterEnco ......

    uj5u.com 2023-05-05 08:18:42 more
  • Spring原始碼:Bean生命周期(三)

    在之前的文章中,我們已經對 `bean` 的準備作業進行了講解,包括 `bean` 定義和 `FactoryBean` 判斷等。在這個基礎上,我們可以更加深入地理解 `getBean` 方法的實作邏輯,并在后續的學習中更好地掌握`createBean` 方法的實作細節。 ......

    uj5u.com 2023-05-05 08:18:35 more
  • Java 雙指標專案中的實際應用

    背景說明 最近在做財務相關的系統,對賬單核銷預付款從技術角度來看就是將兩個陣列進行合并 對賬單核銷預付款前提條件: 對賬單總金額必須等于未核銷金額 資料示例 對賬單資料 | 單號 | 金額 | | | | | B0001 | 100 | | B0002 | 80 | | B0003 | 120 | ......

    uj5u.com 2023-05-05 08:18:30 more
  • Java練手專案(尚硅谷的),不涉及框架,資料庫等。

    軟體:idea 我是先建立了一個空白的專案,自己創建的src包和其下面的包。 **問題一:**建立包之后發現格式為src.com.tjp.bean 沒辦法建立其他與bean同級的service test utils view 等。只允許繼續建立bean的子包。 解決: 這是因為idea自動會折疊空白 ......

    uj5u.com 2023-05-05 08:12:43 more
  • Python教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Python由荷蘭數學和計算機科學研究學會的吉多·范羅蘇姆于1990年代初設計,作為一門叫做ABC語言的替代品。 Python提供了高效的高級資料結構,還能簡單有效地面向物件編程。Python語法和動態型別,以及解釋型語言的本質,使它成為多數平臺上寫腳本和快速開發應用的編程語言, [2] ......

    uj5u.com 2023-05-05 08:06:50 more
  • JUC并發編程原理精講(原始碼分析)

    并發編程是指在程式中使用多執行緒技術來實作并行處理的能力。多執行緒機制使得程式可以分解成互不干擾的任務,從而提高了程式執行的效率。并發編程可以通過對執行緒的創建,管理和協作進行控制,以實作更加高效的并發執行。并發編程的優點包括:① 提高程式執行效率:通過多執行緒并行處理,程式的處理速度可以顯著提高。② 增強... ......

    uj5u.com 2023-05-05 08:00:35 more
  • 【pandas基礎】--資料讀取

    資料讀取是第一步,只有成功加載資料之后,后續的操作才有可能。 pandas可以讀取和匯入各種資料格式的資料,如CSV,Excel,JSON,SQL,HTML等,不需要手動撰寫復雜的讀取代碼。 1. 各類資料源 pandas提供了匯入各類常用檔案格式資料的介面,這里介紹3種最常用的加載資料的介面。 1 ......

    uj5u.com 2023-05-05 07:53:23 more
  • 一文吃透Tomcat核心知識點

    架構 首先,看一下整個架構圖。最全面的Java面試網站 接下來簡單解釋一下。 Server:服務器。Tomcat 就是一個 Server 服務器。 Service:在服務器中可以有多個 Service,只不過在我們常用的這套 Catalina 容器的Tomcat 中只包含一個 Service,在 S ......

    uj5u.com 2023-05-05 07:52:47 more
  • SpringBoot匯出Word檔案的三種方式

    SpringBoot匯出Word檔案的三種方式 一、匯出方案 1、直接在Java代碼里創建Word檔案,設定格式樣式等,然后匯出。(略) 需要的見:https://blog.csdn.net/qq_42682745/article/details/120867432 2、富文本轉換后的HTML下載為 ......

    uj5u.com 2023-05-05 07:52:09 more
  • golang推薦的命名規范

    二 golang推薦的命名規范 很少見人總結一些命名規范,也可能是筆者孤陋寡聞, 作為一個兩年的golang 開發者, 我根據很多知名的專案,如 moby, kubernetess 等總結了一些常見的命名規范。 命名規范可以使得代碼更容易與閱讀, 更少的出現錯誤。 檔案命名規范 由于檔案跟包無任何關 ......

    uj5u.com 2023-05-05 07:51:51 more