当前位置:Gxlcms > 数据库问题 > 【codeblocks配置】C对Mysql数据的查询

【codeblocks配置】C对Mysql数据的查询

时间:2021-07-01 10:21:17 帮助过:2人阅读

#include <stdio.h> 2 #include <winsock2.h> 3 #include <mysql.h> 4 /*数据库连接用宏*/ 5 #define HOST "localhost"//本地 6 #define USERNAME "root"//dbms user name 7 #define PASSWORD "123456"//password 8 #define DATABASE "mydb"//database name 9 void query_sql(char* sql); 10 int main() 11 { 12 char *query; 13 query="select * from students";//查询学生表 14 query_sql(query); 15 return 0; 16 } 17 void query_sql(char* sql) 18 { 19 MYSQL my_connection; /*这是一个数据库连接*/ 20 int res; /*执行sql語句后的返回标志*/ 21 MYSQL_RES *res_ptr; /*指向查询结果的指针*/ 22 MYSQL_FIELD *field; /*字段结构指针*/ 23 MYSQL_ROW result_row; /*按行返回的查询信息*/ 24 int row, column; /*查询返回的行数和列数*/ 25 int i, j; 26 /*初始化mysql连接my_connection*/ 27 mysql_init(&my_connection); 28 /*建立mysql连接*/ 29 if (NULL != mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD, 30 DATABASE, 0, NULL, CLIENT_FOUND_ROWS)) /*连接成功*/ 31 { 32 printf("数据库查询query_sql连接成功!\n"); 33 /*设置查询编码为gbk,以支持中文*/ 34 mysql_query(&my_connection, "set names gbk"); 35 res = mysql_query(&my_connection, sql); 36 if (res) /*执行失败*/ 37 { 38 printf("Error: mysql_query !\n"); 39 /*关闭连接*/ 40 mysql_close(&my_connection); 41 } 42 else /*现在就代表执行成功了*/ 43 { 44 /*将查询的結果给res_ptr*/ 45 res_ptr = mysql_store_result(&my_connection); 46 /*如果结果不为空,就把结果print*/ 47 if (res_ptr) 48 { 49 /*取得結果的行数和*/ 50 column = mysql_num_fields(res_ptr); 51 row = mysql_num_rows(res_ptr); 52 printf("查询到 %d 行 \n", row); 53 /*输出結果的字段名*/ 54 for (i = 0; field = mysql_fetch_field(res_ptr); i++) 55 printf("%10s ", field->name); 56 printf("\n"); 57 /*按行输出結果*/ 58 for (i = 1; i < row+1; i++) 59 { 60 result_row = mysql_fetch_row(res_ptr); 61 for (j = 0; j < column; j++) 62 printf("%10s ", result_row[j]); 63 printf("\n"); 64 } 65 } 66 /*不要忘了关闭连接*/ 67 mysql_close(&my_connection); 68 } 69 } 70 else 71 { 72 printf("数据库连接失败"); 73 } 74 }

 

【codeblocks配置】C对Mysql数据的查询

标签:

人气教程排行