通過應(yīng)用程序訪問數(shù)據(jù)庫(kù)
本文介紹如何通過Java、Python或C的應(yīng)用程序訪問RDS數(shù)據(jù)庫(kù)。
參數(shù)說明
示例代碼中的參數(shù)說明如下。
參數(shù) | 說明 |
Host | RDS實(shí)例的內(nèi)網(wǎng)地址或外網(wǎng)地址。
關(guān)于如何查看RDS實(shí)例的內(nèi)外網(wǎng)地址及端口信息,請(qǐng)參見查看或修改內(nèi)外網(wǎng)地址和端口。 |
Port | 若使用內(nèi)網(wǎng)連接,需輸入RDS實(shí)例的內(nèi)網(wǎng)端口。若使用外網(wǎng)連接,需輸入RDS實(shí)例的外網(wǎng)端口。 |
myDatabase | 目標(biāo)數(shù)據(jù)庫(kù)名稱。 |
myUsername | 要訪問RDS實(shí)例的賬號(hào)名稱。 |
myPassword | 賬號(hào)對(duì)應(yīng)的密碼。 |
示例代碼
以下代碼以在數(shù)據(jù)庫(kù)中查詢名為courses表為例,實(shí)際執(zhí)行代碼時(shí),請(qǐng)按實(shí)際情況填寫。
Java示例代碼:
說明以Maven項(xiàng)目為例,請(qǐng)先在pom.xml文件中添加DriverManager依賴,代碼示例:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency>
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class DatabaseConnection { public static void main(String args[]) { 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`"; //輸入希望執(zhí)行的SQL。 resultSet = statement.executeQuery(selectSql); while (resultSet.next()) { System.out.println(resultSet.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } } }
Python3示例代碼:
說明請(qǐng)先安裝PyMySQL。
Python3安裝命令:
pip3 install PyMySQL
Python2安裝命令:
pip install pymysql==0.9.3
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) finally: connection.close()
C示例代碼:
說明請(qǐng)先安裝mysql.h頭文件,以CentOS為例,執(zhí)行如下命令:
sudo yum install mysql-devel
#include <stdio.h> #include <mysql.h> #include <string.h> int main(void) { MYSQL *t_mysql; MYSQL_RES *res = NULL; MYSQL_ROW row; char *query_str = NULL; int rc, i, fields; int rows; char select[] = "select * from courses"; // 輸入希望執(zhí)行的SQL。 t_mysql = mysql_init(NULL); if(NULL == t_mysql){ printf("init failed\n"); } if(NULL == mysql_real_connect(t_mysql, "<Host>", "<myUsername>", "<myPassword>", "<myDatabase>", <Port>, NULL, 0)){ printf("connect failed\n"); } if(mysql_real_query(t_mysql, select, strlen(select)) != 0){ printf("select failed\n"); } res = mysql_store_result(t_mysql); if (NULL == res) { printf("mysql_restore_result(): %s\n", mysql_error(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_close(t_mysql); }
連接失敗
連接失敗時(shí),建議根據(jù)報(bào)錯(cuò)信息來解決連接問題。