Overview
Scenarios
Product Architecture
Instance Types
Compatibility Notes
Usage specification recommendations
mysql -h$host -P$port -u$user_name -p$password -D$database_name
Parameter | Description |
$host | TDSQL Boundless database connection IP address or domain name and port (default is 3306).OLTP Access Address: To obtain the peer node VIP address and port number, log in to the console, navigate to the Instance Details page, and locate the Basic Info section. The peer node VIP can be found in the Private Network Address field, and the peer node Port is available in the Private Port field. |
$port | |
$user_name | |
$password | |
$database_name | The name of the database to be accessed. |
CREATE, INSERT, DROP, and SELECT privileges on the database.mysql -h192.168.1.100 -P3306 -utest_user -p****** -Dtest_db
## On Ubuntu/Debian systems, please use the following code for installation:sudo apt-get updatesudo apt-get install libmysqlclient-dev## On CentOS/RHEL systems, please use the following code for installation:sudo yum install mysql-devel## Verify whether the installation was successfulmysql_config --version
mysql_config --version command will output the version number of the installed MySQL client library.test.c file in the text editor and save it. The code is as follows:#include <stdio.h>#include <stdlib.h>#include <mysql/mysql.h>int main() {MYSQL *conn = mysql_init(NULL); // Initialize the MySQL connectionif (conn == NULL) {fprintf(stderr, "mysql_init() failed\\n");return 1;}// Connect to the TDSQL Boundless database server// Replace the following parameters with actual connection informationif (mysql_real_connect(conn, "host", "user", "passwd", "db", 3306, NULL, 0) == NULL) {fprintf(stderr, "mysql_real_connect() failed: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}printf("Successfully connected to the TDSQL Boundless database!\\n");// Set the character set to utf8mb4if (mysql_set_character_set(conn, "utf8mb4") != 0) {fprintf(stderr, "Failed to set character set: %s\\n", mysql_error(conn));}// Create a user tableif (mysql_query(conn, "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), PRIMARY KEY(id))") != 0) {fprintf(stderr, "Failed to create table: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}printf("Table created successfully!\\n");// Insert data.if (mysql_query(conn, "INSERT INTO users (name, email) VALUES ('Xiaoming', 'xiaoming@example.com')") != 0) {fprintf(stderr, "Failed to insert data: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}printf("Data inserted successfully!\\n");// Query data.if (mysql_query(conn, "SELECT * FROM users") == 0) {MYSQL_RES *result = mysql_store_result(conn);if (result != NULL) {int num_fields = mysql_num_fields(result);MYSQL_ROW row;printf("\\nQuery results:\\n");printf("----------------------------------------\\n");while ((row = mysql_fetch_row(result))) {for (int i = 0; i < num_fields; i++) {printf("%s ", row[i] ? row[i] : "NULL");}printf("\\n");}printf("----------------------------------------\\n");printf("Total %lu records\\n", (unsigned long)mysql_num_rows(result));mysql_free_result(result);} else {fprintf(stderr, "Failed to obtain result set: %s\\n", mysql_error(conn));}} else {fprintf(stderr, "Failed to query data: %s\\n", mysql_error(conn));}mysql_close(conn); // Close the connectionprintf("Database connection closed.\\n");return 0;}
test.c.vi test.c or vim test.c command to edit the test.c file and modify the database connection information to ensure it matches the actual situation.test.c The database connection information in the file is as follows:// This connection information needs to be modified to the actual connection string information you obtained, as shown in the following exampleif (mysql_real_connect(conn, "192.168.1.100", "test_user", "your_password", "test_db", 3306, NULL, 0) == NULL) {fprintf(stderr, "mysql_real_connect() failed: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}
gcc -o test test.c `mysql_config --cflags --libs`
gcc -o test test.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
test will be generated../test
Successfully connected to the TDSQL Boundless database!Table created successfully!Data inserted successfully!Query results:----------------------------------------1 Xiaoming xiaoming@example.com----------------------------------------There is 1 record.Test table cleaned.Database connection closed.
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <mysql/mysql.h>int main() {MYSQL *conn = mysql_init(NULL);MYSQL_STMT *stmt;MYSQL_BIND bind[2];char name[64] = "Zhang San";char email[128] = "zhangsan@example.com";unsigned long name_length;unsigned long email_length;if (conn == NULL) {fprintf(stderr, "mysql_init() failed\\n");return 1;}// Connect to the TDSQL Boundless databaseif (mysql_real_connect(conn, "host", "user", "passwd", "db", 3306, NULL, 0) == NULL) {fprintf(stderr, "mysql_real_connect() failed: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}// Set the character setmysql_set_character_set(conn, "utf8mb4");// Ensure the table existsmysql_query(conn, "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), PRIMARY KEY(id))");// Initialize the prepared statementstmt = mysql_stmt_init(conn);if (stmt == NULL) {fprintf(stderr, "mysql_stmt_init() failed\\n");mysql_close(conn);return 1;}// Prepare the SQL statementconst char *sql = "INSERT INTO users (name, email) VALUES (?, ?)";if (mysql_stmt_prepare(stmt, sql, strlen(sql))) {fprintf(stderr, "mysql_stmt_prepare() failed: %s\\n", mysql_stmt_error(stmt));mysql_stmt_close(stmt);mysql_close(conn);return 1;}// Bind parametersmemset(bind, 0, sizeof(bind));// Parameter 1: namename_length = strlen(name);bind[0].buffer_type = MYSQL_TYPE_STRING;bind[0].buffer = name;bind[0].buffer_length = sizeof(name);bind[0].length = &name_length;// Parameter 2: emailemail_length = strlen(email);bind[1].buffer_type = MYSQL_TYPE_STRING;bind[1].buffer = email;bind[1].buffer_length = sizeof(email);bind[1].length = &email_length;if (mysql_stmt_bind_param(stmt, bind)) {fprintf(stderr, "mysql_stmt_bind_param() failed: %s\\n", mysql_stmt_error(stmt));mysql_stmt_close(stmt);mysql_close(conn);return 1;}// Execute the prepared statementif (mysql_stmt_execute(stmt)) {fprintf(stderr, "mysql_stmt_execute() failed: %s\\n", mysql_stmt_error(stmt));mysql_stmt_close(stmt);mysql_close(conn);return 1;}printf("Prepared statement executed successfully! Insert ID: %lu\\n", (unsigned long)mysql_stmt_insert_id(stmt));mysql_stmt_close(stmt);mysql_close(conn);return 0;}
#include <stdio.h>#include <stdlib.h>#include <mysql/mysql.h>int main() {MYSQL *conn = mysql_init(NULL);int success = 1;if (conn == NULL) {fprintf(stderr, "mysql_init() failed\\n");return 1;}// Connect to the TDSQL Boundless databaseif (mysql_real_connect(conn, "host", "user", "passwd", "db", 3306, NULL, 0) == NULL) {fprintf(stderr, "mysql_real_connect() failed: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}mysql_set_character_set(conn, "utf8mb4");// Disable auto-commit, begin transaction.if (mysql_autocommit(conn, 0)) {fprintf(stderr, "Failed to disable auto-commit: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}printf("Begin transaction...\\n");// Execute the first SQL statementif (mysql_query(conn, "UPDATE accounts SET balance = balance - 100 WHERE user_id = 1")) {fprintf(stderr, "SQL 1 execution failed: %s\\n", mysql_error(conn));success = 0;}// Execute the second SQL statementif (success && mysql_query(conn, "UPDATE accounts SET balance = balance + 100 WHERE user_id = 2")) {fprintf(stderr, "SQL 2 execution failed: %s\\n", mysql_error(conn));success = 0;}if (success) {// Commit the transaction.if (mysql_commit(conn)) {fprintf(stderr, "Failed to commit the transaction: %s\\n", mysql_error(conn));} else {printf("Transaction committed successfully!\\n");}} else {// Roll back transactionif (mysql_rollback(conn)) {fprintf(stderr, "Failed to rollback the transaction: %s\\n", mysql_error(conn));} else {printf("Transaction rolled back\\n");}}// Re-enable auto-commitmysql_autocommit(conn, 1);mysql_close(conn);return 0;}
#include <stdio.h>#include <stdlib.h>#include <mysql/mysql.h>int main() {MYSQL *conn = mysql_init(NULL);MYSQL_RES *result;MYSQL_ROW row;MYSQL_FIELD *fields;unsigned int num_fields;unsigned int i;if (conn == NULL) {fprintf(stderr, "mysql_init() failed\\n");return 1;}// Connect to the TDSQL Boundless databaseif (mysql_real_connect(conn, "host", "user", "passwd", "db", 3306, NULL, 0) == NULL) {fprintf(stderr, "mysql_real_connect() failed: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}mysql_set_character_set(conn, "utf8mb4");// Execute the query.if (mysql_query(conn, "SELECT id, name, email FROM users ORDER BY id DESC LIMIT 100")) {fprintf(stderr, "Query failed: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}// Obtain the result setresult = mysql_store_result(conn);if (result == NULL) {fprintf(stderr, "Failed to obtain result set: %s\\n", mysql_error(conn));mysql_close(conn);return 1;}// Obtain the field count and field informationnum_fields = mysql_num_fields(result);fields = mysql_fetch_fields(result);// Print column namesprintf("\\n");for (i = 0; i < num_fields; i++) {printf("%-20s", fields[i].name);}printf("\\n");// Print the separator linefor (i = 0; i < num_fields; i++) {printf("--------------------");}printf("\\n");// Traverse the result setwhile ((row = mysql_fetch_row(result)) != NULL) {for (i = 0; i < num_fields; i++) {printf("%-20s", row[i] ? row[i] : "NULL");}printf("\\n");}printf("\\nTotal %lu rows of data\\n", (unsigned long)mysql_num_rows(result));// Free the result setmysql_free_result(result);mysql_close(conn);return 0;}
Function | Description |
mysql_init() | Initialize the MySQL connection handle |
mysql_real_connect() | Connect to the database server |
mysql_close() | Close the database connection |
mysql_query() | Execute the SQL statement |
mysql_store_result() | Obtain the complete result set |
mysql_use_result() | Obtain the result set row by row |
mysql_fetch_row() | Obtain the next row of data |
mysql_num_rows() | Obtain the number of rows of the result set |
mysql_num_fields() | Obtain the number of columns of the result set |
mysql_fetch_fields() | Obtain field information |
mysql_affected_rows() | Obtain the number of affected rows |
mysql_free_result() | Release the result set |
mysql_error() | Get Error Information |
mysql_errno() | Obtain error code |
mysql_set_character_set() | Set character set |
mysql_autocommit() | Set autocommit mode |
mysql_commit() | Commit transaction |
mysql_rollback() | Roll back transaction |
mysql_stmt_init() | Initialize prepared statement |
mysql_stmt_prepare() | Prepare prepared statement. |
mysql_stmt_bind_param() | Bind parameters to the prepared statement. |
mysql_stmt_execute() | Execute the prepared statement. |
mysql_stmt_close() | Close the prepared statement. |
fatal error: mysql/mysql.h: No such file or directory# Installing Development Librariessudo apt-get install libmysqlclient-dev # Ubuntu/Debiansudo yum install mysql-devel # CentOS/RHEL# Use mysql_config to obtain the correct compilation parametersgcc -o test test.c `mysql_config --cflags --libs`
error while loading shared libraries: libmysqlclient.so# Method 1: Add the library path to the environment variablesexport LD_LIBRARY_PATH=/usr/lib/mysql:$LD_LIBRARY_PATH# Method 2: Update the dynamic link library cachesudo ldconfig
utf8mb4 after connecting.mysql_set_character_set(conn, "utf8mb4");
unsigned int timeout = 30;mysql_options(conn, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);
Apakah halaman ini membantu?
Anda juga dapat Menghubungi Penjualan atau Mengirimkan Tiket untuk meminta bantuan.
masukan