因为工作需要, 所以写了这个关于LINUX C操作MYSQL数据库的Demo, 欢迎各位大牛指正.
上代码: cmysql.h
- #include "/usr/include/mysql/mysql.h"
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #define HOST "192.168.16.178"
- #define USERNAME "root"
- #define PASSWORD "123456"
- #define DATABASE "demo"
- extern int bt_connect(MYSQL * my_conn);
- extern int bt_select(MYSQL * my_conn, char * sql, MYSQL_RES ** res_ptr);
- extern int bt_close_db(MYSQL * my_conn);
cmysql.c
- #include "cmysql.h"
- int main(void)
- {
- MYSQL my_conn;
- MYSQL_RES * res_ptr;
- MYSQL_FIELD * field;
- MYSQL_ROW result_row;
- int row = 0, column = 0;
- int i, j;
- if (bt_connect(&my_conn) == -1)
- {
- printf("连接数据库失败!\n");
- return -1;
- }
- if (bt_select(&my_conn, "select * from member", &res_ptr) == -1)
- {
- printf("Error: 查询失败!\n");
- return -2;
- }
- //printf("结果传出的指针: %d\n", *res_ptr);
- if (res_ptr) // 查询到值, 不为空
- {
- column = mysql_num_fields(res_ptr);
- row = mysql_num_rows(res_ptr) + 1;
- printf("共有 %d 列!\n", column);
- printf("查询到 %d 行!\n", row);
- for (i = 0; field = mysql_fetch_field(res_ptr); i++)
- {
- printf("%s\t", field->name);
- }
- printf("\n");
- //按行输出结果
- for (i = 1; i < row; i++)
- {
- result_row = mysql_fetch_row(res_ptr);
- for (j = 0; j < column; j++)
- {
- printf("%s\t", result_row[j]);
- }
- printf("\n");
- }
- }
- bt_close_db(&my_conn);
- return 0;
- }
- extern int bt_connect(MYSQL * my_conn)
- {
- mysql_init(my_conn);
- if (mysql_real_connect(my_conn, HOST, USERNAME, PASSWORD,
- DATABASE, 0, NULL, CLIENT_FOUND_ROWS))
- {
- printf("连接数据库成功!\n");
- return 0;
- }
- else
- {
- return -1;
- }
- }
- extern int bt_select(MYSQL * my_conn, char * sql, MYSQL_RES ** res_ptr)
- {
- int res; // sql执行返回标志
- mysql_query(my_conn, "SET NAMES UTF8");
- res = mysql_query(my_conn, sql);
- //printf("%s\n", sql);
- if (res) // 执行失败
- {
- // printf("Error: 查询失败!\n");
- return -1;
- }
- else
- {
- *res_ptr = mysql_store_result(my_conn);
- //printf("结果指针: %d\n", *res_ptr);
- return 0;
- }
- }
- extern int bt_close_db(MYSQL * my_conn)
- {
- mysql_close(my_conn);
- return 0;
- }
最近编译安装:
gcc -o mysqlDemo cmysql.h cmysql.c -L /usr/local/mysql/lib/*.a -lpthread -ldl
-lz
转载请注明来自派啦网
转载于:https://blog.51cto.com/typedef/901528