1、添加依赖
<!– https://mvnrepository.com/artifact/com.alibaba/druid –>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
2、基本的方法
需要美化的SQL可以直接调用如下方法:
formatMysql(String sql)
formatOdps(String sql)
formatOracle(String sql)
formatPGSql(String sql)
如果数据库类型不是以上四个,还可以
format(String sql,String dbType)
3、实际测试代码
package com.shucha.deveiface.biz.test;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
/**
* @author tqf
* @Description sql语句格式化
* @Version 1.0
* @since 2022-07-19 11:48
*/
public class SqlFormat {
public static void main(String[] args) {
String mysql = "SELECT *,CASE WHEN UNIX_TIMESTAMP( expire_time ) < UNIX_TIMESTAMP( NOW( ) ) THEN 1 ELSE 0 END state FROM `expire_time_data`;";
mysql(mysql);
String oracle = "SELECT a.TABLE_NAME,b.COMMENTS FROM user_tables a,user_tab_comments b WHERE a.TABLE_NAME=b.TABLE_NAME ORDER BY TABLE_NAME;";
oracleSql(oracle);
String pgsql = "SELECT tablename FROM pg_tables WHERE tablename NOT LIKE 'pg%' AND tablename NOT LIKE 'sql_%' ORDER BY tablename;";
PgSql(pgsql);
sqlFormat(mysql,DbType.mysql);
}
/**
* mysql格式化
* @param sql
*/
public static void mysql(String sql){
System.out.println("Mysql格式化:" + SQLUtils.formatMySql(sql));
}
/**
* oracle格式化
* @param sql
*/
public static void oracleSql(String sql){
System.out.println("Oracle格式化:" + SQLUtils.formatOracle(sql));
}
/**
* pgsql格式化
* @param sql
*/
public static void PgSql(String sql){
System.out.println("postgreSql格式化:" + SQLUtils.format(sql, DbType.postgresql));
}
/**
* sql格式
* @param sql 格式化的语句
* @param dbType 数据库类型
*/
public static void sqlFormat(String sql, DbType dbType){
System.out.println("sql格式化:" + SQLUtils.format(sql, dbType));
}
}
格式化后如下
Mysql格式化:
SELECT *
, CASE
WHEN UNIX_TIMESTAMP(expire_time) < UNIX_TIMESTAMP(NOW()) THEN 1
ELSE 0
END AS state
FROM `expire_time_data`;
Oracle格式化:
SELECT a.TABLE_NAME, b.COMMENTS
FROM user_tables a, user_tab_comments b
WHERE a.TABLE_NAME = b.TABLE_NAME
ORDER BY TABLE_NAME;
postgreSql格式化:
SELECT tablename
FROM pg_tables
WHERE tablename NOT LIKE 'pg%'
AND tablename NOT LIKE 'sql_%'
ORDER BY tablename;
————————————————
版权声明:本文为CSDN博主「码奴生来只知道前进~」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tanqingfu1/article/details/125871021