您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關如何用Java連接Aurora MySQL,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
以下是使用mysql-connector 連接Aurora for mysql:
Workbench 訪問Aurora,跟mysql方式一致,如:
Aurora.example.rds.cn-northwest-1.amazonaws.com.cn
用戶名:root
密碼:root
Eclipse 開發首先在maven添加依賴,如下:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency>
源代碼:
package Aurora.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConnectAurora { public static void main(String[] args) { // TODO Auto-generated method stub //聲明Connection對象 Connection con; String driver = "com.mysql.cj.jdbc.Driver"; //URL指向要訪問的數據庫名mydata String url = "jdbc:mysql:// Aurora.example.rds.cn-northwest-1.amazonaws.com.cn:3306/db3"; //MySQL配置時的用戶名 String user = "root"; //MySQL配置時的密碼 String password = "root"; //遍歷查詢結果集 try { //加載驅動程序 Class.forName(driver); //1.getConnection()方法,連接MySQL數據庫!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); //2.創建statement類對象,用來執行SQL語句!! Statement statement = con.createStatement(); //要執行的SQL語句 String sql = "select * from fileindex"; //3.ResultSet類,用來存放獲取的結果集!! ResultSet rs = statement.executeQuery(sql); System.out.println("-----------------------------------------------------------------------------------------------"); System.out.println("------------------------------------------------------------------------------------------------"); System.out.println("| "+ "id" + "\t" +" | "+ "app_id"+ "\t" +" | "+ "文件名字"+ "\t" +" | " + "文件地址"+ "\t" +" | "); System.out.println("------------------------------------------------------------------------------------------------"); String APP_ID = null; String id = null; String address = null; String school = null; while(rs.next()){ //獲取stuname這列數據 id = rs.getString("ID"); //獲取stuid這列數據 APP_ID = rs.getString("APP_ID"); address= rs.getString("File_Name"); school=rs.getString("File_url"); //輸出結果 System.out.println(" | "+id + "\t" +" | "+ APP_ID +" | "+ "\t" +" | "+address +" | "+ "\t" +" | "+school +" | " ); System.out.println(" ------------------------------------------------------------------"); } rs.close(); con.close(); } catch(ClassNotFoundException e) { //數據庫驅動類異常處理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //數據庫連接失敗異常處理 e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("數據庫數據成功獲取!"); } } }
Workbench 查詢:
Java 查詢結果:
以上就是如何用Java連接Aurora MySQL,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。