本帖最后由 feiMathRandom 于 2024-12-31 18:07 编辑
···[Java] 纯文本查看 复制代码 package com.hn.dm.cli;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.setting.Setting;
import java.io.Console;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class DmCli {
private static Log log = LogFactory.get(DmCli.class);
public static void main(String[] args) throws SQLException {
init();
}
public static void init() throws SQLException {
String settingPath = System.getProperty("settingPath");
Setting setting = null;
if (StrUtil.isNotBlank(settingPath)) {
setting = new Setting(settingPath,false);
}else {
setting = new Setting("db.setting");
}
String url = setting.get("url");
System.out.println("数据库连接地址:"+url);
String dbName = JdbcUrlUtil.findDataBaseNameByUrl(url);
Db db = Db.use();
Connection conn = db.getConnection();
while (true) {
String sql = getConsoleSql();
if (StrUtil.isBlank(sql)) {
continue;
}
if ("exit".equals(sql)) {
System.exit(1);
}
sql = StrUtil.trimStart(sql).replaceAll(";","");
try {
if (sql.startsWith("select")) {
select(conn, sql);
} else if("show tables".equals(sql)) {
select(conn,StrUtil.format("select TABLE_NAME from dba_tables where owner='{}'",dbName));
}else if(sql.startsWith("show columns from ")) {
String tabName = sql.replace("show columns from ", "").toUpperCase();
select(conn,StrUtil.format("select COLUMN_NAME,CONCAT(DATA_TYPE,'(' ,DATA_LENGTH,')') as Type ,NULLABLE,DATA_DEFAULT from all_tab_columns" +
" where owner='{}' and Table_Name='{}'",dbName,tabName));
} else {
execute(conn,sql);
}
}catch (Exception e){
log.error(e);
}
}
}
private static String getConsoleSql() {
Console console = System.console();
if (console != null) {
System.out.println("请输入SQL语句:");
return console.readLine();
} else {
// System.err.println("无法获取控制台对象");
return getScannerSql();
}
}
private static String getScannerSql() {
System.out.println("请输入SQL语句:");
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
private static void select(Connection conn, String sql) throws SQLException {
List<Entity> entityList = SqlExecutor.query(conn, sql, new EntityListHandler());
if (entityList.size() > 0) {
Entity entity = entityList.get(0);
Set<String> fieldNames = entity.getFieldNames();
List<List<String>> totalList = new ArrayList<>();
for (Entity entity1 : entityList) {
List<String> data = new ArrayList<>();
for (String fieldName : fieldNames) {
data.add(String.valueOf(entity1.getStr(fieldName)));
}
totalList.add(data);
}
String[][] data = TablePrintExample.convertToListArray(totalList);
// 表头数据
String[] headers = fieldNames.toArray(new String[0]);
// 计算每列的最大宽度
int[] columnWidths = TablePrintExample.calculateColumnWidths(headers, data);
// 打印表头
TablePrintExample.printTableRow(headers, columnWidths);
// 打印分隔线
TablePrintExample.printSeparator(columnWidths);
// 打印数据行
for (String[] row : data) {
TablePrintExample.printTableRow(row, columnWidths);
}
}
}
private static void execute(Connection conn, String sql) throws SQLException {
int execute = SqlExecutor.execute(conn, sql);
if (execute > 0) {
System.out.println("执行结果:"+execute);
}
}
}
[Java] 纯文本查看 复制代码 package com.hn.dm.cli;
import cn.hutool.core.util.StrUtil;
public class JdbcUrlUtil {
public static String findDataBaseNameByUrl(String jdbcUrl) {
String database = null;
int pos, pos1;
String connUri;
if (StrUtil.isBlank(jdbcUrl)) {
throw new IllegalArgumentException("Invalid JDBC url.");
}
jdbcUrl = jdbcUrl.toLowerCase();
if (jdbcUrl.startsWith("jdbc:impala")) {
jdbcUrl = jdbcUrl.replace(":impala", "");
}
if (!jdbcUrl.startsWith("jdbc:")
|| (pos1 = jdbcUrl.indexOf(':', 5)) == -1) {
throw new IllegalArgumentException("Invalid JDBC url.");
}
connUri = jdbcUrl.substring(pos1 + 1);
if (connUri.startsWith("//")) {
if ((pos = connUri.indexOf('/', 2)) != -1) {
database = connUri.substring(pos + 1);
}
} else {
database = connUri;
}
if (database.contains("?")) {
database = database.substring(0, database.indexOf("?"));
}
if (database.contains(";")) {
database = database.substring(0, database.indexOf(";"));
}
if (StrUtil.isBlank(database)) {
throw new IllegalArgumentException("Invalid JDBC url.");
}
return database;
}
}
[Java] 纯文本查看 复制代码 package com.hn.dm.cli;
import java.util.ArrayList;
import java.util.List;
public class TablePrintExample {
public static void main(String[] args) {
// 表头数据
String[] headers = {"ID", "Name", "Age"};
// 示例数据行,这里将二维数组转为List<List<String>>
List<List<String>> data = new ArrayList<>();
List<String> row1 = new ArrayList<>();
row1.add("1");
row1.add("Alice");
row1.add("25");
data.add(row1);
List<String> row2 = new ArrayList<>();
row2.add("2");
row2.add("Bob");
row2.add("30");
data.add(row2);
List<String> row3 = new ArrayList<>();
row3.add("3");
row3.add("Charlie");
row3.add("35");
data.add(row3);
// 计算每列的最大宽度
int[] columnWidths = calculateColumnWidths(headers, convertToListArray(data));
// 打印表头
printTableRow(headers, columnWidths);
// 打印分隔线
printSeparator(columnWidths);
// 打印数据行
for (List<String> row : data) {
printTableRow(row.toArray(new String[0]), columnWidths);
}
}
// 计算每列的最大宽度
public static int[] calculateColumnWidths(String[] headers, String[][] data) {
int numColumns = headers.length;
int[] widths = new int[numColumns];
for (int i = 0; i < numColumns; i++) {
widths[i] = headers[i].length();
}
for (String[] row : data) {
for (int i = 0; i < numColumns; i++) {
widths[i] = Math.max(widths[i], row[i].length());
}
}
return widths;
}
// 打印一行数据(表头或普通数据行)
public static void printTableRow(String[] row, int[] columnWidths) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < row.length; i++) {
sb.append(String.format("| %-" + columnWidths[i] + "s ", row[i]));
}
sb.append("|");
System.out.println(sb.toString());
}
// 打印分隔线
public static void printSeparator(int[] columnWidths) {
StringBuilder sb = new StringBuilder();
for (int width : columnWidths) {
sb.append("+");
for (int j = 0; j < width + 2; j++) {
sb.append("-");
}
}
sb.append("+");
System.out.println(sb.toString());
}
// 将List<List<String>>转换为String[][],用于计算列宽的方法中(因为原方法参数是二维数组)
public static String[][] convertToListArray(List<List<String>> list) {
String[][] result = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i).toArray(new String[0]);
}
return result;
}
}
|