Java读取数据库表(二)

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: 2436846019@qq.com
* @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: 2436846019@qq.com
* @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中出现过。

Java读取数据库表(二)的更多相关文章

  1. (转)java读取数据库表信息,子段

    import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sq ...

  2. Java 导出数据库表信息生成Word文档

    一.前言 最近看见朋友写了一个导出数据库生成word文档的业务,感觉很有意思,研究了一下,这里也拿出来与大家分享一波~ 先来看看生成的word文档效果吧 下面我们也来一起简单的实现吧 二.Java 导 ...

  3. Java判断数据库表是否存在的方法

    一.需求 最近在写一个程序,需要取数据库表的数据之前,需要先查看数据库是否存在该表否则就跳过该表. 二.解决方案(目前想到两种,以后遇到还会继续添加): .建立JDBC数据源,通过Java.sql.D ...

  4. Java获取数据库表 字段 存储的部分数据

    在浏览器页面,选中图片(可多选) >单击删除按钮. 重点是, 本数据库表TabHeBeiTianQi中 存在 同一id,对应的picLocalPath字段  存储了多张图片,图片地址用   逗号 ...

  5. java怎样读取数据库表中字段的数据类型?

    用DriverManager.getConnection()得到connect, 用connect.getMetaData()得到 DatabaseMetaData, 用 DatabaseMetaDa ...

  6. java 读取数据库中表定义

    将数据库中的表信息读取出来 package com.cloud.smartreport.utils; import java.sql.Connection; import java.sql.Datab ...

  7. java读取mysql表的注释及字段注释

    /** * 读取mysql某数据库下表的注释信息 * * @author xxx */ public class MySQLTableComment { public static Connectio ...

  8. Java读取数据库中的xml格式内容,解析后修改属性节点内容并写回数据库

    直接附代码: 1.测试用的xml内容 <mxGraphModel> <root> <mxCell id="-1" /> <mxCell i ...

  9. Java逆向工程(数据库表生成java类)

    说起来倒是挺简单的,就是听着名字感觉挺高大上.逆向工程方式有很多,比如mybatis就提供了一个这样的工具mybatis-genderator,这个我反正是没用过只是听说过,以前在公司都是用公司写好的 ...

  10. JAVA 根据数据库表内容生产树结构JSON数据

    1.利用场景 组织机构树,通常会有组织机构表,其中有code(代码),pcode(上级代码),name(组织名称)等字段 2.构造数据(以下数据并不是组织机构数据,而纯属本人胡编乱造的数据) List ...

随机推荐

  1. idea修改背景颜色|护眼色|项目栏背景修改

    https://blog.csdn.net/heytyrell/article/details/89743068

  2. 修改密码 MVC

    控制器site public function actionPassword(){ $model = new PasswordForm(); /*判断请求属性 if ($request->isA ...

  3. CentOS7-mysql5.7.35安装配置

    一.下载网址 注:mysql从5.7的某个版本之后之后不再提供my-default.cnf文件,不耽误启动,想要自定义配置可以自己去/etc下创建my.cnf文件 全版本:https://downlo ...

  4. python之序列化与反序列化

    #!/usr/bin/env python# -*- coding:utf-8 -*-#Author:QiFeng Zhang'''序列化反序列化之json应用'''import json #导入js ...

  5. Spring设计模式——单例模式

    单例模式 单例模式(Singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点. 单例模式是创建型模式. 饿汉单例模式 饿汉单例模式在类的加载时候就立即初始 ...

  6. Nginx如何升级Openssl

    1. 什么是Openssl? 在计算机网络上,OpenSSL是一个开放源代码的软件库包,应用程序可以使用这个包来进行安全通信,避免窃听,同时确认另一端连线者的身份.这个包广泛被应用在互联网的网页服务器 ...

  7. Eigen 中的 conservativeResize 和 resize 操作

    Eigen 中的 conservativeResize 和 resize 操作 对于能够改变大小的动态矩阵,一般会有 resize() 操作. resize() 如果不改变原矩阵的大小,则原矩阵大小和 ...

  8. 顺应潮流,解放双手,让ChatGPT不废话直接帮忙编写可融入业务可运行的程序代码(Python3.10实现)

    众所周知,ChatGPT可以帮助研发人员编写或者Debug程序代码,但是在执行过程中,ChatGPT会将程序代码的一些相关文字解释和代码段混合着返回,如此,研发人员还需要自己进行编辑和粘贴操作,效率上 ...

  9. DES & 3DES 简介 以及 C# 和 js 实现【加密知多少系列】

    〇.简介 1.DES 简介 DES 全称为 Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,1977 年被美国联邦政府的国家标准局确定为联邦资料处理标准( ...

  10. Lua基础语法学习笔记

    Lua是一门语言,我们可以使用一个库,可以在运行时去编译执行Lua中的代码,从而实现自己的内存中的数据和逻辑: 准备学习环境: 新建一个Lua项目目录,用来写我们的Lua代码: 进入目录,右键使用vs ...