c语言连接mysql数据库的实现方法

时间:2021-05-20

我这里也有一份网上找到的:/201205/other/C_link_mySql51.rar
C连接MySql5.1所需文件.rar
附带一个不错的例子:

#include <string.h> #include <stdlib.h> #include <stdio.h> #include <winsock2.h> #include <mysql/mysql.h> #pragma comment(lib,"libmysql") #define HOST "localhost" #define USERNAME "root" #define PASSWORD "123456" #define DATABASE "test" void exe_sql(char* sql) { MYSQL my_connection; int res; mysql_init(&my_connection); if (mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, CLIENT_FOUND_ROWS)) { printf("数据库执行exe_sql连接成功!n"); mysql_query(&my_connection, "set names utf8"); res = mysql_query(&my_connection, sql); if (res) { printf("Error: mysql_query !\n"); mysql_close(&my_connection); } else { printf("%d 行受到影响!\n", mysql_affected_rows(&my_connection)); mysql_close(&my_connection); } } else { printf("数据库执行exe_sql连接失败!\n"); } } void query_sql(char* sql) { MYSQL my_connection; int res; MYSQL_RES *res_ptr; MYSQL_FIELD *field; MYSQL_ROW result_row; int row, column; int i, j; mysql_init(&my_connection); if (mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, CLIENT_FOUND_ROWS)) { printf("数据库查询query_sql连接成功!\n"); mysql_query(&my_connection, "set names utf8"); *下面这句话就是用mysql_query函数来执行我们刚刚传入的sql語句, 这会返回一个int值,如果为0,证明語句执行成功*/ res = mysql_query(&my_connection, sql); if (res) { printf("Error: mysql_query !\n"); mysql_close(&my_connection); } else { res_ptr = mysql_store_result(&my_connection); if (res_ptr) { column = mysql_num_fields(res_ptr); row = mysql_num_rows(res_ptr) + 1; printf("查询到 %lu 行 \n", row); for (i = 0; field = mysql_fetch_field(res_ptr); i++) printf("%st", field->name); printf("\n"); for (i = 1; i < row; i++) { result_row = mysql_fetch_row(res_ptr); for (j = 0; j < column; j++) printf("%st", result_row[j]); printf("\n"); } } mysql_close(&my_connection); } } } int main(int argc, char *argv[]) { char *query; char *exe = "insert into student values('lala','hahhahah!');"; exe_sql(exe); *测试下查询*/ query="select * from student;"; query_sql(query); return 0; }

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章