Access a database from an application

更新时间:
复制 MD 格式

This topic describes how to access a lightweight database from an application written in Java, Python, or C.

Parameter descriptions

The following table describes the parameters in the sample code.

Parameter

Description

Host

The private or public endpoint of the lightweight database service instance.

  • If your client is deployed on a Simple Application Server instance in the same region as the database, use the private endpoint. For example, if both your Simple Application Server instance and your lightweight database service instance are in the China (Hangzhou) region, using the private endpoint provides a secure and efficient connection.

  • In other cases, you must use the public endpoint.

For more information about how to view the endpoints and port information of a lightweight database service instance, see View details.

Port

The port is 3306.

myDatabase

The name of the destination database.

myUsername

The name of the account used to access the lightweight database service instance. The default value is administrator.

myPassword

The password for the account. If you forget the password, see Reset the database password to change the password for the lightweight database service.

Sample code

The following sections provide sample code in Java, Python, and C.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;

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`";            // Enter the SQL statement that you want to execute.
            resultSet = statement.executeQuery(selectSql);

            while (resultSet.next()) {
                System.out.println(resultSet.getString("name"));
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
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`"        # Enter the SQL statement that you want to execute.
        cursor.execute(sql)
        for result in cursor:
             print(result)
finally:
    connection.close()
#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;

    char select[] = "select * from courses";    // Enter the SQL statement that you want to execute.
    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))) {
        for (i = 0; i < fields; i++) {
            printf("%s\t", row[i]);
        }
        printf("\n");
    }
    mysql_close(t_mysql);

}