如何用Java连接Aurora MySQL

利用Java 访问Aurora

以下是使用mysql-connector 连接Aurora for mysql参考示例
Workbench 访问Aurora,跟mysql方式一致,如:
Aurora.example.rds.cn-northwest-1.amazonaws.com.cn
用户名:root
密码:root
如何用Java连接Aurora MySQL_第1张图片
Eclipse 开发首先在maven添加依赖,如下:



mysql

mysql-connector-java

8.0.15


源代码:

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" + "	" +" | "+ "app_id"+ "	" +" | "+ "文件名字"+ "	" +" | " + "文件地址"+ "	" +" | ");

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 + "	" +" | "+ APP_ID +" | "+ "	" +" | "+address +" | "+ "	" +" | "+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连接Aurora MySQL_第2张图片
Java 查询结果:
如何用Java连接Aurora MySQL_第3张图片
光环云社群是光环云生态伙伴计划,致力于与推广者实现普惠科技,以社会化营销来驱动数字中国。加入光环云社群后将获得AWS产品推广返现、AWS认证优惠、技术文章获取等特权,并得到光环云多项权益赋能支持。

微信搜索“光环云社群”或扫描下方二维码,获取更多资讯
如何用Java连接Aurora MySQL_第4张图片

你可能感兴趣的:(如何用Java连接Aurora MySQL)