Get the App
SLTechnology News&Howtos  ›  Database  › 

How to access MySQL database in C language

Shulou Source: shulou.com Published: 2022-05-31 20:46:12 10月05日 Update

This article is to share with you about how to access the MySQL database in C language. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

First, set up a MySQL user rick with a password of 6452079 and a login location of local login localhost.

Create a database foo for rick users.

Create a table children in the database foo.

The table is structured as follows:

After adding 3 simple records, the table is as follows:

Lab C code:

# include # include # include "mysql.h" MYSQL my_connection;MYSQL_RES * res_ptr;MYSQL_ROW sqlrow;void mysql_display_row (MYSQL * my_connect, MYSQL_ROW sqlrow) {unsigned int field_count; unsigned int field_result = mysql_field_count (my_connect); field_count = 0; while (field_count

< field_result ) { printf("%s ", sqlrow[field_count]); field_count++; } printf("\n");}int main(){ int res; mysql_init( &my_connection ); if( NULL != mysql_real_connect( &my_connection, "localhost", "rick", "6452079", "foo", 0, NULL, 0 ) ) { printf("Connection success!\n"); res = mysql_query( &my_connection, "SELECT childno, fname, age FROM children WHERE age>

5 "); if (0! = res) printf (" SELECT error:% s\ n ", mysql_error (& my_connection)); else {res_ptr = mysql_use_result (& my_connection); if (NULL! = res_ptr) {/ / printf (" Retrieved% lu rows\ n ", (unsigned long) mysql_num_rows (res_ptr)) While ((sqlrow = mysql_fetch_row (res_ptr) {printf ("Fetched data...\ n"); mysql_display_row (& my_connection, sqlrow) } if (0! = mysql_errno (& my_connection)) fprintf (stderr, "Retrieve error:% s\ n", mysql_error (& my_connection)); mysql_free_result (res_ptr);} mysql_close (& my_connection) }} else {fprintf (stderr, "Connection failed\ n"); if (mysql_errno (& my_connection)) fprintf (stderr, "Connection error% d:% s\ n", mysql_errno (& my_connection), mysql_error (& my_connection));} return EXIT_SUCCESS;}

Running result:

The above is how to access the MySQL database in C language. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Data database language more user knowledge article login utility code location password that is work meeting article look knowledge point structure result industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Technology macOS Microsoft Shulou Information