C++设置管理员实现数据库的增删改查
时间: 2023-11-14 11:27:24 浏览: 109
c++实现数据库的连接以及对应的增删改查功能
要实现管理员对数据库的增删改查,需要先连接数据库,然后使用SQL语句来进行相关操作。以下是一个简单的示例程序:
```c++
#include <iostream>
#include <mysql.h> // 请确保已经安装mysql库,并在编译时链接mysql库
using namespace std;
int main()
{
// 连接数据库
MYSQL mysql;
mysql_init(&mysql);
mysql_real_connect(&mysql, "localhost", "root", "password", "database_name", 0, NULL, 0);
// 显示菜单,让管理员选择操作
int choice;
do {
cout << "Please choose the operation you want to perform: " << endl;
cout << "1. Add record" << endl;
cout << "2. Delete record" << endl;
cout << "3. Update record" << endl;
cout << "4. Query record" << endl;
cout << "0. Exit" << endl;
cin >> choice;
switch (choice) {
case 1: // 添加记录
{
string name;
int age;
cout << "Please input name and age: ";
cin >> name >> age;
string sql = "INSERT INTO table_name (name, age) VALUES ('" + name + "', " + to_string(age) + ")";
mysql_query(&mysql, sql.c_str());
cout << "Record added successfully!" << endl;
}
break;
case 2: // 删除记录
{
string name;
cout << "Please input name: ";
cin >> name;
string sql = "DELETE FROM table_name WHERE name='" + name + "'";
mysql_query(&mysql, sql.c_str());
cout << "Record deleted successfully!" << endl;
}
break;
case 3: // 修改记录
{
string name;
int age;
cout << "Please input name and new age: ";
cin >> name >> age;
string sql = "UPDATE table_name SET age=" + to_string(age) + " WHERE name='" + name + "'";
mysql_query(&mysql, sql.c_str());
cout << "Record updated successfully!" << endl;
}
break;
case 4: // 查询记录
{
string name;
cout << "Please input name: ";
cin >> name;
string sql = "SELECT * FROM table_name WHERE name='" + name + "'";
mysql_query(&mysql, sql.c_str());
MYSQL_RES *result = mysql_store_result(&mysql);
if (result) {
MYSQL_ROW row;
while ((row = mysql_fetch_row(result))) {
cout << "Name: " << row[0] << ", Age: " << row[1] << endl;
}
mysql_free_result(result);
}
}
break;
case 0: // 退出程序
break;
default: // 无效的选择
cout << "Invalid choice!" << endl;
break;
}
} while (choice != 0);
// 断开数据库连接
mysql_close(&mysql);
return 0;
}
```
需要注意的是,上面的代码中使用了字符串拼接来构建SQL语句,这样会导致SQL注入攻击的风险,应该避免在实际应用中使用。可以使用参数化查询来解决这个问题。同时,上面的示例代码也没有进行错误处理,实际应用中应该对函数返回值进行检查,以便及时发现并解决错误。
阅读全文