The following articles mainly describe the actual operation process of reading the MySQL database in C language. If you are interested in the correct operation process of reading the MySQL database in C language, the following articles will satisfy your curiosity.
Recently, we learned about C development in the linux operating system. Haha, I wrote a test program to read MySQL Data and display it. Tested successfully...
- #include <stdio.h>
- #include <stdlib.h>
- #include <MySQL.h>
- #define DB_SERVER ""
- #define DB_NAME "test"
- #define DB_USER "root"
- #define DB_PWD ""
- static MySQL *db_handel,MySQL;
- static MySQL_ROW row;
- static int query_error;
- MySQL_RES *query_test(char *sql);
- int query_show(MySQL_RES *result);
- int main(int argc,char *argv[])
- {
- MySQL_RES * results;
- results=query_test("select * from test");
Retrieve records
- query_show(results);
Show records
- return 0;
- }
Query records
- MySQL_RES *query_test(char *sql)
- {
- static MySQL_RES *query_result;
- printf("%s\n",sql);
- MySQL_init(&MySQL);
- db_handel=MySQL_real_connect(&MySQL,DB_SERVER,DB_USER,DB_PWD,DB_NAME,0,0,0);
Open the connection to read the MySQL database
- if(db_handel==NULL)
Error Handling
{
- printf(MySQL_error(&MySQL));
- return NULL;
- }
- query_error=MySQL_query(db_handel,sql);
Query
- if(query_error!=0)
Error Handling
- {
- printf(MySQL_error(db_handel));
- return NULL;
- }
- query_result=MySQL_store_result(db_handel);
Retrieve records
- MySQL_close(db_handel);
Close Database
- return query_result;
Return record
- }
Show records
- int query_show(MySQL_RES *result)
- {
- unsigned int i,num_fields;
- MySQL_FIELD *fileds;
- num_fields=MySQL_num_fields(result);
Obtain the number of fields
- fileds= mysql _fetch_fields(result);
Get field array
- while((row=mysql_fetch_row(result))!=NULL)
Loop display
- {
- for(i=0;i<num_fields;i++)
- {
- printf("%s: %s \n",fileds[i].name,row[i]?row[i]:"NULL");
- }
- }
- return 0;
- }
The contents of MakeFile are as follows:
- CC=gcc
- #LDLIBS=`gtk-config --libs --cflags`
- LDLIBS=-L /usr/lib/mysql -I /usr/include/mysql -l mysqlclient
- CFLAGS=-Wall -g`gtk-config --cflags`
- window:window.c
- $(CC) $(LDLIBS) window.c -o window
- #window.o:window.c
- # $(CC) $(LDLIBS) -c window.c
- clean:
- rm -f window
- rm -f *.o
The above content is an introduction to reading Mysql from the C language. I hope you will get some benefits.