SQLServer多版本兼容Java方案和數據采集

Maven引入

<dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>4.0</version></dependency><dependency><groupId>net.sourceforge.jtds</groupId><artifactId>jtds</artifactId><version>1.3.1</version></dependency>

連接創建

// 數據庫URL,用戶名和密碼String connectionUrl = "jdbc:jtds:sqlserver://"+dataSource.getIp()+":"+dataSource.getPort()+";databaseName="+dataSource.getDatabaseName()+";user="+dataSource.getUserName()+";password="+dataSource.getPassword()+";";try {Class.forName("net.sourceforge.jtds.jdbc.Driver");} catch (ClassNotFoundException e) {throw new RuntimeException("當前不支持的SQLServer驅動版本");}

查詢樣例(SQLServer通用數據采集)

表內容查詢

public List<List<JSONObject>> importData(DataSourceImportDataVO dataSourceImportDataVO) {List<List<JSONObject>> rtn = new ArrayList<>();// 創建SQLServer連接TbDataSource dataSource = dataSourceImportDataVO.getDataSource();Long dataCollectJobId = dataSourceImportDataVO.getDataCollect().getId();if (!DataSourceLinkTypeEnum.SQLSERVER.getTypeCode().equals(dataSource.getLinkType())){// 配置的連接不是SQLServer類型collectStatusMQService.send(dataCollectJobId, CollectJobRunStatusTypeEnum.CONNECT_FAILED);collectRecordMQService.send(dataSourceImportDataVO, CollectJobRunStatusTypeEnum.CONNECT_FAILED, "", "");throw new CustomException("數據源不是 SQLServer 連接");}SQLServerDataDealBaseService dataDealBaseService =(SQLServerDataDealBaseService) dataSourceImportDataVO.getDataDealBaseService();// 開始時間Date date = new Date();// 文件類型和文件名稱枚舉值// 數據庫連接URL,格式為:jdbc:sqlserver://服務器地址:端口號;databaseName=數據庫名String connectionUrl = "jdbc:jtds:sqlserver://"+dataSource.getIp()+":"+dataSource.getPort()+";databaseName="+dataSource.getDatabaseName();try {Class.forName("net.sourceforge.jtds.jdbc.Driver");} catch (ClassNotFoundException e) {// 數據源連接失敗:可能發身在數據源連接創建過程中,或后續數據查詢過程中,都算做連接失敗collectStatusMQService.send(dataCollectJobId, CollectJobRunStatusTypeEnum.CONNECT_FAILED);collectRecordMQService.send(dataSourceImportDataVO, CollectJobRunStatusTypeEnum.CONNECT_FAILED, "", "");return new ArrayList<>();}// 數據庫用戶和密碼String user = dataSource.getUserName();String password = dataSource.getPassword();List<JSONObject> datas = new ArrayList<>();try (Connection con = DriverManager.getConnection(connectionUrl, user, password);Statement stmt = con.createStatement()) {SQLServerDealVO sqlServerDealVO = new SQLServerDealVO();sqlServerDealVO.setConnection(con);sqlServerDealVO.setStatement(stmt);sqlServerDealVO.setTableName(dataSourceImportDataVO.getDataCollect().getFileType());sqlServerDealVO.setDataSourceImportData(dataSourceImportDataVO);sqlServerDealVO.setDataCollectJobId(dataCollectJobId);// 預置連接成功,后邊查詢數據過程中可能還會出現連接失敗的情況,通過SQLException捕捉collectStatusMQService.send(dataCollectJobId, CollectJobRunStatusTypeEnum.CONNECT_SUCCESS);datas = dataDealBaseService.fromSQLServer(sqlServerDealVO);rtn.add(datas);} catch (SQLException e) {// 發送作業MQ狀態log.error("【SQLServer 連接創建失敗】 ", e);// 數據源連接失敗:可能發身在數據源連接創建過程中,或后續數據查詢過程中,都算做連接失敗collectStatusMQService.send(dataCollectJobId, CollectJobRunStatusTypeEnum.CONNECT_FAILED);collectRecordMQService.send(dataSourceImportDataVO, CollectJobRunStatusTypeEnum.CONNECT_FAILED, "", "");return new ArrayList<>();}catch (DataParsingException e){// 發送作業MQ狀態log.error("【SQLServer 數據解析失敗】 ", e);collectRecordMQService.send(dataSourceImportDataVO, CollectJobRunStatusTypeEnum.PARSE_FAILED, JSON.toJSONString(datas), "采集數據源中的表 "+dataSourceImportDataVO.getDataCollect().getFileType()+" 或該表同步字段 "+dataSourceImportDataVO.getDataCollect().getSynchronousField()+" 不存在");return new ArrayList<>();}log.info("【數據接入】【SQLServer】處理完成 耗時 {} 秒 ", (new DateBetween(date, new Date())).between(DateUnit.SECOND));return rtn;}

表名稱獲取

public List<String> getDataSourceTables(TbDataSource dataSource) {// 數據庫URL,用戶名和密碼String connectionUrl = "jdbc:jtds:sqlserver://"+dataSource.getIp()+":"+dataSource.getPort()+";databaseName="+dataSource.getDatabaseName()+";user="+dataSource.getUserName()+";password="+dataSource.getPassword()+";";List<String> tables = new ArrayList<>();try {Class.forName("net.sourceforge.jtds.jdbc.Driver");} catch (ClassNotFoundException e) {throw new RuntimeException("當前不支持的SQLServer驅動版本");}try (Connection connection = DriverManager.getConnection(connectionUrl)) {// 創建Statement對象來執行查詢Statement statement = connection.createStatement();// 執行查詢獲取所有表名ResultSet resultSet = statement.executeQuery("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");// 遍歷結果集while (resultSet.next()) {tables.add(resultSet.getString("TABLE_NAME"));}} catch (SQLException e) {e.printStackTrace();}return tables;}

字段名稱獲取

/**
* SQLServer 2005后版本判斷
*/
private final String pattern = "對象名\\s+'.*?'\\s+無效";public List<GetSourceColumnOutputDTO> getSourceColumns(TbDataSource dataSource, String tableName) {// 數據庫URL,用戶名和密碼String connectionUrl = "jdbc:jtds:sqlserver://" + dataSource.getIp() + ":" + dataSource.getPort() + ";databaseName="+ dataSource.getDatabaseName() + ";user=" + dataSource.getUserName() + ";password=" + dataSource.getPassword() + ";";List<GetSourceColumnOutputDTO> colums = new ArrayList<>();try {Class.forName("net.sourceforge.jtds.jdbc.Driver");} catch (ClassNotFoundException e) {throw new RuntimeException("當前不支持的SQLServer驅動版本");}try (Connection connection = DriverManager.getConnection(connectionUrl)) {
//            // 獲取DatabaseMetaData對象
//            DatabaseMetaData metaData = connection.getMetaData();
//
//            // 查詢表的列名
//            ResultSet resultSet = metaData.getColumns(null, null, tableName, "%");// 創建Statement對象來執行查詢Statement statement = connection.createStatement();String sql = "SELECT \n" +"     CONVERT(NVARCHAR(100), c.name) AS ColumnName,\n" +"    CONVERT(NVARCHAR(100),ep.value) AS ColumnComment\n" +"FROM \n" +"    sys.columns c\n" +"INNER JOIN \n" +"    sys.objects o ON c.object_id = o.object_id\n" +"LEFT OUTER JOIN \n" +"    sys.extended_properties ep ON ep.major_id = c.object_id \n" +"                                AND ep.minor_id = c.column_id \n" +"                                AND ep.name = 'MS_Description'\n" +"WHERE \n" +String.format("    o.name = '%s' \n", tableName) +"ORDER BY \n" +"    c.column_id;";// 執行查詢獲取所有表名ResultSet resultSet = null;try {resultSet = statement.executeQuery(sql);} catch (SQLException e) {// sys.extended_properties等 是 SQL Server 2005 引入的系統視圖,用于存儲擴展屬性信息。SQL Server 2000 及更早版本中沒有這個視圖。if (e.getMessage().matches(".*" + pattern + ".*")){sql = "SELECT \n" +"        CONVERT(NVARCHAR(100), sc.name) AS ColumnName,\n" +"        CONVERT(NVARCHAR(100), sp.value) AS ColumnComment\n" +"    FROM \n" +"        syscolumns sc\n" +"    INNER JOIN \n" +"        sysobjects so ON sc.id = so.id\n" +"    LEFT OUTER JOIN \n" +"        sysproperties sp ON sp.id = sc.id \n" +"                          AND sp.smallid = sc.colid \n" +"                          AND sp.name = 'MS_Description'\n" +"    WHERE \n" +String.format("    so.name = '%s' \n", tableName) +"    ORDER BY \n" +"        sc.colid";resultSet = statement.executeQuery(sql);}}if (Objects.isNull(resultSet)) {return colums;}// 遍歷結果集int sort = 1;while (resultSet.next()) {GetSourceColumnOutputDTO tmp = new GetSourceColumnOutputDTO();String columnName = resultSet.getString("ColumnName");String columnComment = resultSet.getString("ColumnComment");tmp.setName(StringUtils.isEmpty(columnComment) ? columnName : columnComment);tmp.setCode(columnName);tmp.setOriginCode(columnName);tmp.setSort(sort++);colums.add(tmp);}} catch (SQLException e) {e.printStackTrace();}return colums;}
public class GetSourceColumnOutputDTO implements Serializable {private static final long serialVersionUID = 1L;@ApiModelProperty(value = "字段中文名")private String name;@ApiModelProperty(value = "源字段編碼")private String code;@ApiModelProperty(value = "源字段原始編碼")private String originCode;@ApiModelProperty(value = "源字段協議中的排序")private Integer sort;}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/81151.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/81151.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/81151.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【每日八股】復習 Redis Day4:線程模型

文章目錄 復習 Redis Day4&#xff1a;線程模型介紹一下 Redis 的線程模型核心線程模型&#xff08;Redis 6.0 之前&#xff09;Redis 6.0 的多線程改進Redis 真的是單線程嗎&#xff1f;Redis 的線程模型剖析 上一篇 Redis 的應用我今天才完成&#xff0c;因此明天一并復習 Re…

樹莓派智能攝像頭實戰指南:基于TensorFlow Lite的端到端AI部署

引言&#xff1a;嵌入式AI的革新力量 在物聯網與人工智能深度融合的今天&#xff0c;樹莓派這一信用卡大小的計算機正在成為邊緣計算的核心載體。本文將手把手教你打造一款基于TensorFlow Lite的低功耗智能監控設備&#xff0c;通過MobileNetV2模型實現實時物體檢測&#xff0…

vs2019編譯occ7.9.0時,出現fatal error C1060: compiler is out of heap space

問題描述 visual studio 2019編譯opencascade 7.9.0時&#xff0c;出現編譯錯誤 fatal error C1060: compiler is out of heap space 解決方案 修改vs2019并行編譯的線程個數&#xff0c;默認是12個&#xff0c;我改成了4個&#xff0c;問題解決 Tools > Project and Sol…

vue跨域問題總結筆記

目錄 一、Websocket跨域問題 1.nginx配置 2.VUE CLI代理 3.env.development配置 4.nginx日志 5.解決 一、解決跨域的幾種常用方法 1.Vue CLI代理 2.JSONP 3.WebSocket 4.NGINX解決跨域問題 6.Java解決跨域 二、Vue跨域問題詳解 1. 什么是跨域 2. 跨域的例子 3.…

數據結構篇:線性表的另一表達—鏈表之單鏈表(下篇)

目錄 1.前言 2.是否使用二級指針 3.插入/刪除 3.1 pos位置前/后插入 3.2 查找函數 3.3 pos位置刪除 3.4 pos位置后面刪除 3.5 函數的銷毀 4.斷言問題 4.1 斷言pphead 4.2 斷言*pphead 5.三個文件的代碼 5.1 頭文件 5.2 具體函數實現 5.3 測試用例 1.前言 之前是講…

完美解決react-native文件直傳阿里云oss問題一

前言 通常情況下&#xff0c;作為前后端分離的項目來說&#xff0c;文件上傳是最尋常的功能之一。雖然每個公司選擇的文件管理云庫各不相同&#xff0c;但實現思路基本一致。我所在公司使用阿里云oss文件管理&#xff0c;之前服務端做了透傳&#xff0c;但是由于每個測試環境的…

5.運輸層

5. 運輸層 1. 概述 第2~4章依次介紹了計算機網絡體系結構中的物理層、數據鏈路層和網絡層&#xff0c;它們共同解決了將主機通過異構網絡互聯起來所面臨的問題&#xff0c;實現了主機到主機的通信然而在計算機網絡中實際進行通信的真正實體&#xff0c;是位于通信兩端主機中的…

告別手動時代!物聯網軟件開發讓萬物自動互聯

清晨&#xff0c;智能窗簾隨著陽光自動拉開&#xff1b;運動時&#xff0c;手表精準記錄著健康數據&#xff1b;回到家&#xff0c;室溫早已調節至最舒適狀態...這些場景的實現&#xff0c;都離不開物聯網軟件開發的技術支撐。在智能家居軟件開發、智能穿戴軟件開發、醫療器械軟…

Fiori學習專題十二:Shell Control as Container

為了讓我們的app更加適應不同的設備&#xff0c;這節課我們引入shell控件作為根元素 1.修改App.view.xml&#xff0c;加入Shell控件 <mvc:ViewcontrollerName"ui5.walkthrough.controller.App"xmlns"sap.m"xmlns:mvc"sap.ui.core.mvc"displa…

AI 與高性能計算的深度融合:開啟科技新紀元

在當今科技迅猛發展的時代&#xff0c;人工智能&#xff08;AI&#xff09;與高性能計算&#xff08;HPC&#xff09;正以前所未有的態勢深度融合&#xff0c;這種融合宛如一場強大的風暴&#xff0c;席卷并重塑著眾多領域的格局。從科學研究的突破到商業應用的革新&#xff0c…

「Unity3D」TextMeshPro使用TMP_InputField實現,輸入框高度自動擴展與收縮

先看實現效果&#xff1a; 要實現這個效果&#xff0c;有三個方面的問題需要解決&#xff1a; 第一&#xff0c;輸入框的高度擴展&#xff0c;內部子元素會隨著錨點&#xff0c;拉伸變形——要解決這個問題&#xff0c;需要將內部元素改變父類&#xff0c;然后增加父類高度&am…

多模態大語言模型arxiv論文略讀(四十七)

AdaShield: Safeguarding Multimodal Large Language Models from Structure-based Attack via Adaptive Shield Prompting ?? 論文標題&#xff1a;AdaShield: Safeguarding Multimodal Large Language Models from Structure-based Attack via Adaptive Shield Prompting …

美的人形機器人即將投入實際應用

國內家電巨頭美的集團近日公布了其自主研發的人形機器人的具體落地計劃。根據公司披露的信息&#xff0c;這款機器人將于5月在湖北荊州的洗衣機工廠率先投入使用&#xff0c;承擔設備運維、質量檢測和物料搬運等工作任務。預計今年下半年&#xff0c;該機器人還將進入美的線下門…

從零開始搭建你的個人博客:使用 GitHub Pages 免費部署靜態網站

&#x1f310; 從零開始搭建你的個人博客&#xff1a;使用 GitHub Pages 免費部署靜態網站 在互聯網時代&#xff0c;擁有一個屬于自己的網站不僅是一種展示方式&#xff0c;更是一種技術能力的體現。今天我們將一步步學習如何通過 GitHub Pages 搭建一個免費的個人博客或簡歷…

canvas動畫:點隨機運動 距離內自動連接成線 鼠標移動自動吸附附近的點

思路/實現步驟 創建canvas元素 獲取canvas的上下文ctx 初始化點的信息&#xff08;數量、初始坐標、移動方向、移動速度、大小、顏色&#xff09; 繪制點 繪制點之間的連線 點有規律的動起來 動畫循環 鼠標移動相關邏輯 點鼠標之間連線 鼠標吸附邏輯 添加配置項 重繪…

2025年4月AI科技領域周報(4.21-4.27):大模型生態加速演進 通用AI開啟產業融合新范式

2025年4月AI科技領域周報&#xff08;4.21-4.27&#xff09;&#xff1a;大模型生態加速演進 通用AI開啟產業融合新范式 一、本周熱點回顧1. OpenAI發布全球首款通用AI芯片「GPT-NPU」 重塑AI算力架構2. 谷歌DeepMind發布醫療AI系統「Med-Pathfinder」 實現全科室智能診斷3. 微…

【Bash】可以請您解釋性地說明一下“2>1”這個語法嗎?

Qwen3-235B 當然可以&#xff01;我們一步步拆解 2>&1 的含義&#xff0c;用生活化的例子來理解它&#xff1a; &#x1f9e0; 前提知識&#xff1a;三個“水流通道” 在 Linux/Unix 系統中&#xff0c;程序運行時有三種默認的“水流通道”&#xff1a; 標準輸入&…

MAC如何安裝多版本jdk(以8,11,17為例)

MAC如何安裝多版本jdk(以8,11,17為例&#xff09;_mac安裝jdk17-CSDN博客

Nginx核心

一、概述 Nginx一個具有高性能的【HTTP】和【反向代理】的【WEB服務器】&#xff0c;同時也是一個電子郵件代理服務器。正向代理服務的是客戶端&#xff08;比如VPN&#xff09;&#xff0c;反向代理服務的是服務端。Nginx是多進程的&#xff0c;有一個Master進程控制多個Worke…

綜合開發-手機APP遠程控制PLC1500柱燈的亮滅

要通過 ??Unity3D?? 開發的手機 App 控制 ??電氣柜上面的柱燈&#xff0c;需要WIFI模塊作為橋梁&#xff0c;按照以下步驟實現&#xff1a; ??1. 硬件準備&#xff08;硬件部分&#xff09;?? ??所需材料?? ??ESP32開發板??&#xff08;如ESP32-WROOM-32&a…