Codeblocks writing C files to connect to MySQL database
Codeblocks settings.
1. Set the Lib library file:
Settings->compiler settings->linker settings->link libraries:add add C:\Program files\mysql\mysql Server 5.5\ Lib\libmysql.lib
2. Set the. h header file:
Settings->compiler settings->search directories->compiler:add add C:\Program Files\Microsoft SDKs\Windows\ V6.0a\include
The above two steps can only be introduced.
[3. Note Libmysql.dll file, if the file is lost can be downloaded, downloaded and placed under C:\Windows\System32]
C->mysql Querying data
1#include <stdio.h>2#include <winsock2.h>3#include <mysql.h>4 /*Macros for database connections*/5 #defineHOST "localhost"//Local6 #defineUSERNAME "Root"//DBMS User name7 #definePASSWORD "123456"//Password8 #defineDATABASE "MyDB"//Database name9 voidQuery_sql (Char*sql);Ten intMain () One { A Char*query; -query="SELECT * FROM Students";//Check Student Form - query_sql (query); the return 0; - } - voidQuery_sql (Char*sql) - { +MYSQL my_connection;/*This is a database connection*/ - intRes/*return flag after executing a SQL sentence*/ +Mysql_res *res_ptr;/*pointer to query result*/ AMysql_field *field;/*field structure Pointer*/ atMysql_row Result_row;/*query information returned by row*/ - introw, column;/*Number of rows and columns returned by the query*/ - intI, J; - /*initializing MySQL connection my_connection*/ -Mysql_init (&my_connection); - /*establish a MySQL connection*/ in if(NULL! = Mysql_real_connect (&my_connection, HOST, USERNAME, PASSWORD, -DATABASE,0, NULL, Client_found_rows))/*Connection Successful*/ to { +printf"database query Query_sql connection succeeded! \ n"); - /*set the query encoding to GBK to support Chinese*/ themysql_query (&my_connection,"Set names GBK"); *res = mysql_query (&my_connection, SQL); $ if(RES)/*Execution failed*/Panax Notoginseng { -printf"error:mysql_query!\n"); the /*Close Connection*/ +Mysql_close (&my_connection); A } the Else /*now it's a successful execution.*/ + { - /*give the results of the query to Res_ptr*/ $Res_ptr = Mysql_store_result (&my_connection); $ /*If the result is not empty, print the result*/ - if(res_ptr) - { the /*the number of rows to get the results and*/ -Column =Mysql_num_fields (res_ptr);Wuyirow =mysql_num_rows (res_ptr); theprintf"query to%d lines \ n", row); - /*field name for output results*/ Wu for(i =0; field = Mysql_fetch_field (res_ptr); i++) -printf"%10s", field->name); Aboutprintf"\ n"); $ /*output by rows results*/ - for(i =1; I < row+1; i++) - { -Result_row =mysql_fetch_row (res_ptr); A for(j =0; J < column; J + +) +printf"%10s", Result_row[j]); theprintf"\ n"); - } $ } the /*don't forget to close the connection*/ theMysql_close (&my_connection); the } the } - Else in { theprintf"Database connection Failed"); the } About}
"Codeblocks Configuration" C query for MySQL data