#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#include <unistd.h>
#include <string.h>
int main()
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char server[] = "localhost";
char user[] = "root";
char passwd[] = "xxxxxx";
char database[] = "test";
char *query = NULL;
int number=0;
conn = mysql_init(NULL); //初始化MySQL
if(!mysql_real_connect(conn,server,user,passwd,database,0,NULL,0)) //连接数据库database
{
fprintf(stderr,"mysql connect error:%s\n",mysql_error(conn));
exit(1);
}
query = "create table student (id int(10),name varchar(25),math int(2),chinese int(2))";
if(mysql_real_query(conn,query,strlen(query))) //创建数据表student
{
fprintf(stderr,"mysql query error:%s\n",mysql_error(conn));
exit(1);
}
query = "insert into student values(20220815,\"Ailon\",10,20)";
if(mysql_real_query(conn,query,strlen(query))) //添加数据
{
fprintf(stderr,"mysql query error:%s\n",mysql_error(conn));
exit(1);
}
query = "update student set id=20220001 where id=20220815";
if(mysql_real_query(conn,query,strlen(query))) //更改数据
{
fprintf(stderr,"mysql query error:%s\n",mysql_error(conn));
exit(1);
}
query = "select * from student where math>0";
if(mysql_real_query(conn,query,strlen(query))) //查询数据
{
fprintf(stderr,"mysql query error:%s\n",mysql_error(conn));
exit(1);
}
res = mysql_store_result(conn); //存储查询结果
number = mysql_num_rows(res); //获取结果行数
printf("%d\n",number);
while((row = mysql_fetch_row(res)) !=NULL) //遍历每行
{
printf("id:%d name:%s math:%d chinese:%d\n",atoi(row[0]),row[1],atoi(row[2]),atoi(row[3])); //输出每行数据
}
query = "delete from student where id=20220001";
if(mysql_real_query(conn,query,strlen(query))) //删除特定行数据
{
fprintf(stderr,"mysql query error:%s\n",mysql_error(conn));
exit(1);
}
mysql_free_result(res); //释放资源
mysql_close(conn); //关闭MySQL
exit(0);
}