要求:
#include<mysql.h>
#pragmacomment(lib, "libmysql") //调用libmysql动态库;
MySQL结构体
描述数据库的类,通过connect可以连接到数据现有的数据库;
相关api
int mysql_library_init(int argc, char**argv, char **groups)
mysql_library_init(0,NULL, NULL)
.:初始化MySQL的库函数;
MYSQL *mysql_init(MYSQL *mysql);初始化MySQL类 , 返回值为null的话,空间不足以分配创建对象;
与其对应的为mysql_close(MYSQL *mysql);
MYSQL *mysql_real_connect(MYSQL *mysql, const char *host,const char *user, const char *passwd, const char *db, unsigned int port, constchar *unix_socket, unsigned long client_flag);连接服务器;
常用写法
mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0);
int mysql_query(MYSQL *mysql, const char *stmt_str);
执行由null终止的字符串指向的SQL语句stmt_str
。返回为零则成功,非零就失败;
void mysql_library_end(void);
相关描述:This function finalizes the MySQL library.结束库。
my_ulonglong mysql_affected_rows(MYSQL *mysql);
相关描述:mysql_affected_rows() may be called immediately after executing astatement with mysql_query() or mysql_real_query(). It returns the number ofrows changed, deleted, or inserted by the last statement if it was an UPDATE,DELETE, or INSERT. For SELECT statements, mysql_affected_rows() works likemysql_num_rows().
返回值:被影响的行数;
完整代码
#include <stdio.h>
#include <stdlib.h>
// MySQL supporton Windows
#include <WinSock2.h>
#include <mysql.h>
#pragma comment(lib, "libmysql")
struct student
{
int id;
char name[20];
char birthday[20];
char cellphone[20];
};
int insert(student & stu)
{
MYSQL sql;
if (NULL == mysql_init(&sql))
{
printf("数据库初始化失败\n");
return -1;
}
mysql_real_connect(&sql, "127.0.0.1", "root", "123456", "example", 0, NULL, 0);
char cmd[256];
sprintf_s(cmd,256,
"INSERT INTO `student`"
"(`id`,`name`,`birthday`,`cellphone`)"
"VALUES"
"('%d','%s','%s','%s')"
, stu.id, stu.name, stu.birthday, stu.cellphone);
int ret = mysql_query(&sql, cmd);
if (ret != 0)
{
printf("the error is %s", mysql_errno(&sql));
}
else
{
unsigned long long affected_rows = mysql_affected_rows(&sql);
printf("%d行被影响", (int)affected_rows);
}
mysql_close(&sql);
return 0;
}
int main(void)
{
if (mysql_library_init(0, NULL, NULL))
{
printf("could not initialize MySQL library\n");
return -1;
}
// 获取用户输入
student stu;
char buff[20];
printf("请输入学生ID\n");
gets_s(buff, 20);
stu.id = atoi(buff);
printf("请输入学生姓名\n");
gets_s(stu.name, 20);
printf("请输入学生生日\n");
gets_s(stu.birthday, 20);
printf("请输入学生cellphone\n");
gets_s(stu.cellphone, 20);
insert(stu);
mysql_library_end();
return 0;
}