【发布时间】:2023-03-11 22:00:01
【问题描述】:
我尝试连接mysql和c++。 这是尝试将输入的值放入数据库的过程。 g++编译时出错。
我在 Visual Studio 2017 和 CentOS7 中使用 c++98 进行编码。 使用的Mysql Connector是Mysql++ ver.8.0。
#include "[~ PATH]/mysql++/include/mysql++/cmdline.h"
#include "[~ PATH]/mysql++/include/mysql++/mysql++.h"
#include "[~ PATH]/mysql++/examples/printdata.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
char buffer[256];
string name;
string id;
string password;
string department;
cout << ">> Sign Up <<\n" << endl;
cout << "1.Name: "; cin >> name;
cout << "2.ID: "; cin >> id;
cout << "3.PASSWORD: "; cin >> pw;
cout << "4.Department: "; cin >> dpt;
mysqlpp::Connection conn(false);
if (conn.connect("member_list", "localhost", "user", "password1234"))
{
**mysqlpp::Query query
= conn.query(sprintf(buffer,"INSERT INTO signup_member (name,id,password,department)
VALUES ('%s','%s','%s','%s')",name.c_str(),id.c_str(),password.c_str(),department.c_str()));**
if (mysqlpp::StoreQueryResult res = query.store()) {
cout << "Sign up SUCCESS!" << endl;
}
else {
cerr << "Sign up FAIL. Try again." << '\n' << query.error() << endl;
return 1;
}
return 0;
}
else {
cerr << "DB connection failed: " << conn.error() << endl;
}
}
当我搜索时,它说使用“sprintf”将值保存在缓冲区中,然后将其保存在数据库中。我希望它运作良好,但事实并非如此。
sign_up.cpp:30:175: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]
【问题讨论】:
-
你忘了阅读
sprintf(et al)。 -
顺便说一句,除了最一次性的个人应用程序之外,您应该考虑使用准备好的语句和参数绑定来防止 SQL 注入。例如,请参阅this page。