《数据库系统概论》实验报告 | |
---|---|
题目: 通过嵌入式SQL访问数据库 | |
姓名 | |
日期 | 2021.4.24 |
实验环境:
ubuntu20.04 + mysql8.0.23
实验内容与完成情况:
先尝试db的prep预处理,但对于mysql好像不行,直接调用C-API了。
编译命令g++ lab5API.cpp
mysql_config --cflags --libs-o lab5API
#include <iostream>
#include<mysql/mysql.h>
using namespace std;
int main()
{
MYSQL *conn;
conn = mysql_init(NULL);//初始化
if (conn == NULL) {
perror("init error!");
}
if (mysql_real_connect(conn, "localhost", "root", "",
"S_T", 3306,NULL, 0) == NULL) {
perror("connect error!");
}
int pid;
cout<< "如果想查询课程信息,请输入1, 如果想查询选课信息,请输入2"<< endl;
cin >> pid;
if(pid == 1) {
cout << "请输入课程号" << endl;
string hcno;
cin >> hcno;
string sql = "select * from Course where Cno =";
sql += hcno;sql += ";";//创建查询语句
mysql_query(conn, sql.c_str());//查询
MYSQL_RES *result;
MYSQL_ROW row;
result = mysql_store_result(conn);
int num_fields = mysql_num_fields(result);//获取一个记录的字段数目
while ((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}
}
else if(pid == 2) {
cout << "请输入课程号" << endl;
string hcno;
cin >> hcno;
string sql = "select * from SC where Cno =";
sql += hcno;sql += ";";//创建查询语句
mysql_query(conn, sql.c_str());//查询
MYSQL_RES *result;
MYSQL_ROW row;
result = mysql_store_result(conn);
int num_fields = mysql_num_fields(result);//获取一个记录的字段数目
while ((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_free_result(result);
cout << "如果想修改成绩,请输入1,否则输入0退出" << endl;
cin >> pid;
if(pid == 1) {
string sno, cno, grade;
cout << "请输入学号, 课程号和新的成绩, 以空格隔开"<< endl;
cin >> sno >> cno >> grade;
string update = "update SC set grade=" + grade;
update += " where Sno='" + sno + "' and Cno='" + cno + "';";
cout << update << endl;
if(mysql_query(conn, update.c_str()) != 0){
perror("set error!");
}
cout << "修改后的结果" << endl;
mysql_query(conn, sql.c_str());
result = mysql_store_result(conn);
int num_fields = mysql_num_fields(result);//获取一个记录的字段数目
while ((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}
}
}
}
1、课程信息查询
2、查询选课信息
出现的问题:
先尝试db的prep预处理,但对于mysql好像不行。
解决方案(列出遇到的问题和解决办法,列出没有解决的问题):
直接调用C-API了。