MySql数据库下载地址:https://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.62-win32.zip
环境配置
添加MySql数据库的.h头文件和.lib静态库文件
头文件所在位置:mysql-5.5.62-win32\include\
静态库所在位置:mysql-5.5.62-win32\lib
将mysql-5.5.62-win32\lib\中的libmysql.dll放到编译目录,供编译的程序调用
codeblocks添加方法参考:codeblocks添加h头文件和lib静态库方法
MySql接口函数
链接数据库:mysql_real_connect(con, dbip, dbuser, dbpasswd, dbname, 3306, NULL, 0)
选择数据库:mysql_select_db(con, dbname)
查询语句:mysql_real_query(con, query, strlen(query))
查看错误:mysql_error(con)
获取查询结果记录集:MYSQL_RES *res = mysql_store_result(con)
读取记录集字段值:MYSQL_ROW *row = mysql_fetch_row(res)
实现代码
#include "stdio.h"
#include <winsock2.h>
#include "mysql.h"
int main()
{
MYSQL * con; //= mysql_init((MYSQL*) 0);
MYSQL_RES *res;
MYSQL_ROW row;
char tmp[400];
//database configuartion
char dbuser[30] = "root";
char dbpasswd[30] = "root"; // it must be changed
char dbip[30] = "localhost";
char dbname[50] = "test";
char tablename[50] = "table";
char *query = NULL;
int x;
int y;
int rt;//return value
unsigned int t;
int count = 0;
con = mysql_init((MYSQL*)0);
if (con != NULL && mysql_real_connect(con, dbip, dbuser, dbpasswd, dbname, 3306, NULL, 0)) {
if (!mysql_select_db(con, dbname)) {
printf("成功选择数据库!\n");
con->reconnect = 1;
query = "set names \'GBK\'";
rt = mysql_real_query(con, query, strlen(query));
if (rt) {
printf("查询错误: %s !!!\n", mysql_error(con));
}
else {
printf("查询 %s 成功!\n", query);
}
}
}
else {
MessageBoxA(NULL, "无法连接数据库,请检查配置!", "", NULL);
}
//sprintf(tmp, "insert into %s values(%s,%d,%d)", tablename, "null", x, y); //注意如何向具有自增字段的数据库中插入记录
sprintf(tmp, "insert into table values(null,'x','x','x','x')");
rt = mysql_real_query(con, tmp, strlen(tmp));
if (rt)
{
printf("Error making query: %s !!!\n", mysql_error(con));
}
else
{
printf("%s executed!!!\n", tmp);
}
sprintf(tmp, "select * from %s", tablename);
rt = mysql_real_query(con, tmp, strlen(tmp));
if (rt)
{
printf("Error making query: %s !!!\n", mysql_error(con));
}
else
{
printf("%s executed!!!\n", tmp);
}
res = mysql_store_result(con);//将结果保存在res结构体中
while (row = mysql_fetch_row(res)) {
for (t = 0; t<mysql_num_fields(res); t++) {
printf("%s ", row[t]);
}
printf(".............\n");
count++;
}
printf("number of rows %d\n", count);
printf("mysql_free_result...\n");
mysql_free_result(res);
mysql_close(con);
system("pause");
return 0;
}