c++输入变量插入数据库代码
时间: 2023-06-18 15:07:42 浏览: 58
以下是一个简单的示例代码,演示如何使用 C++ 将输入的变量插入数据库(MySQL)中:
```c++
#include <iostream>
#include <mysql.h>
using namespace std;
int main() {
MYSQL* conn;
MYSQL_RES* res;
MYSQL_ROW row;
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, "localhost", "root", "password", "mydatabase", 0, NULL, 0)) {
cout << "Connection Error: " << mysql_error(conn) << endl;
exit(1);
}
string name;
int age;
string gender;
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
cout << "Enter gender: ";
cin >> gender;
string query = "INSERT INTO mytable (name, age, gender) VALUES ('" + name + "', " + to_string(age) + ", '" + gender + "')";
if (mysql_query(conn, query.c_str())) {
cout << "Query Error: " << mysql_error(conn) << endl;
exit(1);
}
mysql_close(conn);
return 0;
}
```
在此示例中,我们通过 MySQL C API 连接到本地 MySQL 数据库,并从用户输入中获取三个值:姓名、年龄和性别。然后,我们使用这些值构建一个 SQL 查询语句,并将其传递给 `mysql_query()` 函数。如果查询失败,我们将输出错误消息并退出程序。否则,我们将关闭数据库连接并退出程序。
请注意,此示例中使用了字符串拼接构建 SQL 查询语句,这可能会引入一些安全问题,例如 SQL 注入攻击。为了避免这些问题,最好使用参数化查询。