Connect to an ApsaraDB RDS for MySQL instance from a Java, Python, or C application using the JDBC driver, PyMySQL library, or the MySQL C API.
Prerequisites
Before you begin, ensure that you have:
-
An ApsaraDB RDS for MySQL instance that is running
-
A database and an account created on the instance
-
The IP address of your application host added to the instance whitelist
Get connection information
Retrieve the internal or public endpoint and port of your RDS instance before writing connection code.
-
Internal endpoint: Use this when your application runs on an Elastic Compute Service (ECS) instance that resides in the same region and has the same network type as the RDS instance.
-
Public endpoint: Use this for all other scenarios, such as connecting from a local machine or an ECS instance in a different region.
For more information, see View and change the internal and public endpoints and port numbers of an ApsaraDB RDS for MySQL instance.
Connection parameters
The following parameters appear in all sample code in this topic.
| Parameter | Description |
|---|---|
<Host> |
The internal or public endpoint of the RDS instance. |
<Port> |
The port number that corresponds to the endpoint type: internal port for internal connections, public port for Internet connections. |
<myDatabase> |
The name of the database. |
<myUsername> |
The username of the account used to connect to the instance. |
<myPassword> |
The password of the account. |
Connect using Java
The Java sample uses JDBC and the mysql-connector-java driver to open a connection and run a SELECT query against the courses table.
Install the driver
Add the following dependency to the pom.xml file in your Maven project:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
Sample code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
public static void main(String args[]) {
// Replace the placeholders with your actual connection details
String connectionUrl = "jdbc:mysql://<Host>:<Port>/<myDatabase>";
ResultSet resultSet;
try (Connection connection = DriverManager.getConnection(connectionUrl, "<myUsername>", "<myPassword>");
Statement statement = connection.createStatement()) {
String selectSql = "SELECT * FROM `courses`";
resultSet = statement.executeQuery(selectSql);
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Expected output
If the connection succeeds and the courses table contains data, each row's name column value is printed to the console:
Introduction to Cloud Computing
Database Fundamentals
Advanced Java Programming
If you see a SQLException stack trace instead, see Troubleshooting.
Connect using Python
The Python sample uses PyMySQL to connect and run a SELECT query against the courses table.
Install PyMySQL
Run the appropriate command for your Python version:
-
Python 3:
pip3 install PyMySQL -
Python 2:
pip install pymysql==0.9.3
Sample code
import pymysql
connection = pymysql.connect(
host='<Host>',
port=<Port>,
user='<myUsername>',
passwd='<myPassword>',
db='<myDatabase>'
)
try:
with connection.cursor() as cursor:
sql = "SELECT * FROM `courses`"
cursor.execute(sql)
for result in cursor:
print(result)
except pymysql.err.OperationalError as e:
if e.args[0] == 1045:
print("Access denied: check your username and password.")
elif e.args[0] == 1049:
print("Unknown database: check the database name.")
else:
print(f"Connection error: {e}")
finally:
connection.close()
Expected output
If the connection succeeds and the courses table contains data, each row is printed as a tuple:
('Introduction to Cloud Computing',)
('Database Fundamentals',)
('Advanced Java Programming',)
Connect using C
The C sample uses the MySQL C API to connect and run a SELECT query against the courses table.
Install the MySQL C library
On CentOS, run:
sudo yum install mysql-devel
Sample code
#include <stdio.h>
#include <mysql.h>
#include <string.h>
int main(void)
{
MYSQL *t_mysql;
MYSQL_RES *res = NULL;
MYSQL_ROW row;
int rc, i, fields;
int rows;
char select[] = "select * from courses";
t_mysql = mysql_init(NULL);
if (NULL == t_mysql) {
printf("init failed\n");
return 1;
}
/* Replace the placeholders with your actual connection details */
if (NULL == mysql_real_connect(t_mysql, "<Host>", "<myUsername>", "<myPassword>",
"<myDatabase>", <Port>, NULL, 0)) {
printf("connect failed: %s\n", mysql_error(t_mysql));
return 1;
}
if (mysql_real_query(t_mysql, select, strlen(select)) != 0) {
printf("select failed: %s\n", mysql_error(t_mysql));
mysql_close(t_mysql);
return 1;
}
res = mysql_store_result(t_mysql);
if (NULL == res) {
printf("mysql_store_result(): %s\n", mysql_error(t_mysql));
mysql_close(t_mysql);
return 0;
}
fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res))) {
for (i = 0; i < fields; i++) {
printf("%s\t", row[i]);
}
printf("\n");
}
mysql_free_result(res);
mysql_close(t_mysql);
return 0;
}
Expected output
If the connection succeeds, each row from the courses table is printed with tab-separated columns:
Introduction to Cloud Computing
Database Fundamentals
Advanced Java Programming
The sample code queries a courses table as an example. Replace the SQL statement and table name with queries that match your actual database schema.
Troubleshooting
If the connection fails, check the error message returned by the driver or library. Common causes include:
-
Incorrect endpoint or port — verify the values from Get connection information
-
Incorrect username or password — double-check the account credentials
-
IP address not added to the whitelist — add the application host IP to the instance whitelist
-
Public endpoint not enabled — enable the public endpoint in the console if connecting from outside the VPC
For a complete troubleshooting guide, see Resolve the issue that you cannot connect to an RDS instance.
What's next
-
To connect from a serverless function, configure VPC access for your function and add the function's IP to the RDS whitelist. See Access an ApsaraDB RDS for MySQL database in the Function Compute documentation.
-
For more Python connection examples, see the start-fc-db repository on GitHub.