达梦数据库在终端/控制台交互查询SQL语句,查询结果导出excel
依赖
安装JDK,maven引入达梦包,maven打包主类改成查询工具类,即可放到linux平台运行
<dependency><groupId>com.dameng</groupId><artifactId>DmJdbcDriver18</artifactId><version>8.1.2.192</version>
</dependency><!--导出excel所需依赖-->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.3</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version>
</dependency>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>org.example.dmtest.DMDatabaseQuery</mainClass></configuration></plugin></plugins>
</build>
操作方法
-
直接运行,或者打包后java -jar运行控制台
-
输入 SQL 查询语句(分号结束)
-
输入 'export ’ 加查询语句,将结果导出为excel;
-
查询语句默认分页前10条,防止数据量过大;
-
支持多行换行输入;
-
支持连续交互,输入 ‘exit;’ 退出;
查询内容:
导出excel:export + 查询sql;
工具类
package org.example.dmtest;import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class DMDatabaseQuery {private static final String URL = "jdbc:dm://ip:端口?schema=模式名";private static final String USER = "用户名";private static final String PASSWORD = "密码";public static void main(String[] args) {try {Class.forName("dm.jdbc.driver.DmDriver"); // 加载驱动try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);Scanner scanner = new Scanner(System.in)) {Statement statement = connection.createStatement();System.out.println("输入 SQL 查询语句(分号结束),输入 'exit;' 退出;输入 'export ' 加查询语句,将结果导出为excel;默认分页前10条;");while (true) {StringBuilder sqlBuilder = new StringBuilder();String line;// 读取多行输入boolean firstLine = true; // 用于标记是否为第一行输入while (true) {if (firstLine) {System.out.print("SQL: ");firstLine = false; // 设置为 false,以后不再显示提示} else {System.out.print(" "); // 后续行缩进显示}line = scanner.nextLine().trim(); // 去掉行首行尾空格// 如果输入为空,继续下一行if (line.isEmpty()) {continue;}sqlBuilder.append(line).append(" "); // 添加到 SQL 字符串// 如果行以分号结尾,则停止读取if (line.endsWith(";")) {break;}}String sql = sqlBuilder.toString().trim();// 检查是否退出if ("exit;".equalsIgnoreCase(sql)) {break;}// 去掉最后的分号if (sql.endsWith(";")) {sql = sql.substring(0, sql.length() - 1).trim();}// 检查是否包含 export,去掉 exportboolean isExport = false;if (sql.trim().toLowerCase().startsWith("export ")) {isExport = true;sql = sql.substring("export ".length()).trim(); // 去掉 export}// 检查并添加 LIMIT 10if (sql.trim().toLowerCase().startsWith("select") && !sql.toLowerCase().contains("limit")) {sql += " LIMIT 10";}System.out.println("执行SQL: " + sql);try {ResultSet resultSet = statement.executeQuery(sql);int columnCount = resultSet.getMetaData().getColumnCount();// 如果需要导出,调用导出方法if (isExport) {exportToExcel(resultSet, columnCount, sql);} else {// 打印表头for (int i = 1; i <= columnCount; i++) {String columnName = resultSet.getMetaData().getColumnName(i);System.out.printf("%-15s", columnName); // 设置列宽}System.out.println(); // 换行// 打印每一行数据while (resultSet.next()) {for (int i = 1; i <= columnCount; i++) {String value = resultSet.getString(i);System.out.printf("%-15s", value); // 设置列宽}System.out.println(); // 换行}}} catch (Exception e) {System.out.println("执行查询时出错: " + e.getMessage());}}} catch (Exception e) {System.out.println("连接数据库时出错: " + e.getMessage());}} catch (ClassNotFoundException e) {System.out.println("找不到数据库驱动: " + e.getMessage());}}private static void exportToExcel(ResultSet resultSet, int columnCount, String sql) {Workbook workbook = new XSSFWorkbook();Sheet sheet = workbook.createSheet("Query Result");try {// 创建表头Row headerRow = sheet.createRow(0);for (int i = 1; i <= columnCount; i++) {String columnName = resultSet.getMetaData().getColumnName(i);Cell cell = headerRow.createCell(i - 1);cell.setCellValue(columnName);}// 写入数据行int rowIndex = 1;while (resultSet.next()) {Row row = sheet.createRow(rowIndex++);for (int i = 1; i <= columnCount; i++) {String value = resultSet.getString(i);Cell cell = row.createCell(i - 1);cell.setCellValue(value);}}// 处理 SQL 查询生成有效的文件名String fileName = generateFileName(sql) + ".xlsx"; // 输出文件名try (FileOutputStream fileOut = new FileOutputStream(fileName)) {workbook.write(fileOut);}System.out.println("数据已成功导出到文件: " + fileName);} catch (Exception e) {System.out.println("导出到 Excel 时出错: " + e.getMessage());} finally {try {workbook.close();} catch (Exception e) {System.out.println("关闭工作簿时出错: " + e.getMessage());}}}// 生成有效的文件名private static String generateFileName(String sql) {// 去掉前导的 "export ",并将所有特殊字符替换为下划线String cleanName = sql.replaceAll("^export\\s+", "").replaceAll("[\\\\/:*?\"<>|]", "_");// 限制文件名长度,避免超出操作系统限制(一般为255字符)return cleanName.length() > 50 ? cleanName.substring(0, 50) : cleanName;}
}