从网上得到的一个已有程序,经过简单修改和调试满足了自己变成的需求,记录一下。。。谢谢前辈们的分享,让我们可以站在巨人的肩膀上学习,进步!!
#include
#include
#include
#include
#include "mysql.h"
#pragma comment(lib,"libmysql")
#define HOST "localhost"
#define USERNAME "root"
#define PASSWORD "123456"
#define DATABASE "ipinfo"
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 gb2312");
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 gb2312"); //utf8应该是可以的,此程序为何不可以,有待认证
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("%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");
}
}
mysql_close(&my_connection);
}
}
}
int main(int argc, char *argv[]) {
char *query;
char *exe = "insert into ipinfo values(0,'192.168.5.4','192.168.5.7','测试信息');"; //序号为零时,编号显示为自动在当前序号加1;如果指定非零的正整数序号,则显示所指定序号
exe_sql(exe);
query="select * from ipinfo;";
query_sql(query);
return 0;
}
调试中遇到的问题:
1、缺少数据库连接文件;
添加所需的数据连接文件,如下图:
设置编码方式:mysql_query(&my_connection,"set names gb2312"); (此处,utf8编码格式应该是可以的,此程序为何不可以,有待认证)
3、插入信息错误;
当时数据的格式和插入信息的数不完善,缺少编号列,所以出现错误。
(在显示信息时,感觉数据有点乱,其实是按一定的格式设置的,我了之后与MySQL数据库的后续操作)