#include <stdio.h>
#include <winsock.h>
#include <mysql.h>
#include <string.h>
struct user {
int id;
char name[10];
int age;
};
typedef struct user User;
//连接数据库
MYSQL* collection()
{
MYSQL* mysql = mysql_init(0);
mysql_real_connect(mysql, "127.0.0.1", "root", "123456", "c_learn", 3306, "", 0);
mysql_query(mysql, "set names gbk");
return mysql;
}
//关闭 mysql 连接
void close_collection(MYSQL* mysql)
{
mysql_close(mysql);
}
// 添加/修改/查询 方法
void executeNoQuery(char *sql)
{
MYSQL* mysql = collection();
if (NULL != mysql)
{
mysql_query(mysql, sql);
}
close_collection(mysql);
}
//查询方法
User* executeQuery(char* sql,User* p)
{
MYSQL* mysql = collection();
if (NULL != mysql)
{
mysql_query(mysql, sql);
//离线结果集 保存在内存中, 适用于小结果集
MYSQL_RES* result = mysql_store_result(mysql);
MYSQL_ROW row;
User* u = p;
while (row = mysql_fetch_row(result))
{
char* id = row[0];
char* name = row[1];
char* age = row[2];
u->id = atoi(id);
strcpy(u->name,name);
u->age = atoi(age);
u++;
}
close_collection(mysql);
}
return p;
}
int main()
{
printf("***********************学生管理系统***********************\n");
while (1)
{
User users[10] = { {0,"",0} };
User* p_user = users;
char* sql = "select * from user";
executeQuery(sql, p_user);
printf("----------------------------------------------------------\n");
printf("学号\t姓名\t年龄\n");
while (p_user->id != 0)
{
printf("%d\t%s\t%d\n", p_user->id, p_user->name, p_user->age);
p_user++;
}
printf("----------------------------------------------------------\n");
printf("1 添加 2 修改 3 删除 4 查询 0 退出\n");
int a;
scanf("%d",&a);
if (a == 1)
{
printf("请按照(姓名 年龄)顺序添加:\n");
char b[10];
int c;
scanf("%s %d",b,&c);
char sql_add[100];
sprintf(sql_add, "insert into user(name,age) values('%s',%d)", b, c);
executeNoQuery(sql_add);
continue;
}
else if (a == 2)
{
printf("请输入要修改的ID:\n");
int b;
scanf("%d",&b);
printf("请按照(姓名 年龄)顺序输入修改的内容:\n");
char c[10];
int d;
scanf("%s %d", c, &d);
char sql_edit[100];
sprintf(sql_edit, "update user set name = '%s',age = %d where id = %d", c, d, b);
executeNoQuery(sql_edit);
continue;
}
else if (a == 3)
{
printf("请输入要删除的ID:\n");
int b;
scanf("%d", &b);
char sql_reomve[100];
sprintf(sql_reomve, "delete from user where id = %d",b);
executeNoQuery(sql_reomve);
continue;
}
else if (a == 4)
{
printf("请输入要查询的ID:\n");
int b;
scanf("%d", &b);
char sql_user[100];
sprintf(sql_user, "select * from user where id = %d", b);
User user = { 0,"",0 };
User* p_user = &user;
executeQuery(sql_user,p_user);
printf("学号\t姓名\t年龄\n");
printf("%d\t%s\t%d\n", p_user->id, p_user->name, p_user->age);
printf("0 退出\n");
int e;
scanf("%d", &e);
if (e == 0)
{
continue;
}
}
else if(a == 0)
{
break;
}
else
{
printf("输入有误,请重新输入:\n");
continue;
}
}
}
07-16
1091
01-03
1万+