This topic describes how to connect to a database in Data Management (DMS) Database Lab by using an application.
Prerequisites
Background information
Step 1: Obtain the connection information of a database
Step 2: Connect to the database by using an application
After you obtain the connection information of the database, use code in an application
to connect to the database. The following code provides examples on how to connect
to in Java, Python, and C.
Note Parameter descriptions:
- Host: the endpoint of the instance to which the database belongs.
- Port: the port of the database.
- myDatabase: the name of the database.
- myUsername: the account that you use to log on to the database.
- myPassword: the password of the account.
- Use Java to connect to the database:
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()) { // Query the courses table. String selectSql = "SELECT * FROM `courses`"; resultSet = statement.executeQuery(selectSql); while (resultSet.next()) { // Display the name column in the courses table. System.out.println(resultSet.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } } }
- Use Python to connect to the database:
import pymysql connection = pymysql.connect(host='Host', port=Port, user='myUsername', passwd='myPassword', db='myDatabase') try: with connection.cursor() as cursor: // Query the courses table. sql = "SELECT * FROM `courses`" cursor.execute(sql) for result in cursor: // Display the query result. print(result) finally: connection.close()
- Use C to connect to the database:
#include <stdio.h> #include <mysql.h> #include <string.h> void main(void) { MYSQL *t_mysql; MYSQL_RES *res = NULL; MYSQL_ROW row; char *query_str = NULL; int rc, i, fields; int rows; // Query the courses table. char select[] = "select * from courses"; 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 -1; } fields = mysql_num_fields(res); while ((row = mysql_fetch_row(res))) { // Display each column in the courses table. for (i = 0; i < fields; i++) { printf("%s\t", row[i]); } printf("\n"); } mysql_close(t_mysql); }