1. 程式人生 > 其它 >JAVA後端呼叫他人MySql資料庫(Gradle)

JAVA後端呼叫他人MySql資料庫(Gradle)

原本使用Oracle資料庫的專案,在後端需要和別的專案對接,第三方專案使用的MySql資料庫的,需要在後臺取到對方資料庫資訊

首先在Gradle的配置檔案中引入所需要的包

compile ("mysql:mysql-connector-java:5.1.39")

在後端拿到資料

  1  @Override
  2     public List<你自己的VO類別或實體類> getCompanionInfo(List<String> idNos) {
  3         String driverClassName = "com.mysql.jdbc.Driver";    //
啟動驅動 4 String url = "jdbc:mysql://111.111.1.111:3306/ysx?useUnicode=true&characterEncoding=UTF-8&useSSL=false"; //設定你自己的連線路徑 5 String username = "嘎嘎嘎資料庫名"; //資料庫使用者名稱 6 String password = "喵喵資料庫密碼"; //資料庫連線密碼 7 Connection con = null; //連線 8 Statement stmt = null
; 9 ResultSet rs = null; //初始化結果集 10 List<Object> list = new ArrayList<>(); 11 List<你自己的VO類或實體類> companionInfoList = new ArrayList<>(); 12 try { 13 Class.forName(driverClassName); //執行驅動 14 con = DriverManager.getConnection(url, username, password); //
獲取連線 15 stmt = con.createStatement(); 16 17 String sql = "你自己的資料庫查詢語句";
66 rs = stmt.executeQuery(sql); 67 68 ResultSetMetaData md = rs.getMetaData(); 69 int columnCount = md.getColumnCount(); 70 71 72 while (rs.next()) { 73 Map<String, Object> rowData = new HashMap<>(); 74 for (int i = 0; i < columnCount; i++) { 75 rowData.put(md.getColumnLabel(i + 1).toLowerCase(),rs.getString(i + 1)); 76 } 77 78 //用自己的類把資料填裝一下 79           80 CompanionInfoVO companionInfoVO = new CompanionInfoVO(); 81 companionInfoVO.setCompanionName((String)rowData.get("你查詢的列別名")); 82 companionInfoVO.setCompanionIdCard((String)rowData.get("你查詢的列別名")); 84 89 90 companionInfoList.add(companionInfoVO); 91 } 92 93 return companionInfoList; 94 } catch (Exception e) { 95 throw new RuntimeException(e); 96 } finally { 97 //關閉資源,倒關 98 try { 99 if (rs != null) rs.close(); 100 if (stmt != null) stmt.close(); 101 if (con != null) con.close(); //必須要關 102 } catch (Exception e) { 103 } 104 } 105 }

嗨嗨害  有用點個贊喔