[英]How can I pass user-defined variable into MySQL Database Table using C++?
我已经创建了 MySQL 数据库,我想将用户定义的变量(年龄和年级)添加到数据库表中。 我不知道如何将变量包含到我的数据库中的表中。 代码粘贴在下面。
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
using namespace std;
int main()
{
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "127.0.0.1", "root", "password", "test", 0, NULL, 0);
if (conn)
{
cout << "Connected" << endl;
}
else
cout << "Not Connected";
int grade;
int age;
cout << "Enter Age and Grade" << endl;
cin >> age;
cin >> grade;
mysql_query(conn, "CREATE TABLE test1 ( AGE INT, GRADE INT)");
mysql_query(conn, "INSERT INTO test (AGE, GRADE) VALUES (age, grade)"; //I am asking about this part
mysql_close(conn);
return 0;
}
我对 MySQL 库不是很熟悉,但是根据他们对您正在使用的 function 的文档,我认为您应该简单地创建一个 function 来创建您的声明来格式化您的声明。 你可以使用sprintf 。
对于那些正在寻找答案的人(由于堆栈溢出缩进系统可能会出现语法错误)。
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
using namespace std;
int main()
{
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "127.0.0.1", "root", "password", "test", 0, NULL, 0);
if (conn)
{
cout << "Connected" << endl;
}
else
cout << "Not Connected";
string name;
string city;
cout << "Enter name and city: " << endl;
cin >> name;
cin >> city;
mysql_query(conn, "CREATE TABLE test1 ( NAME VARCAR (50), CITY CARCHAR (50)");
mysql_query(conn, "INSERT INTO test ('NAME', 'CITY') VALUES ('"+age+"',
'"+grade+"'))";
mysql_close(conn);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.