【问题标题】:How to fix 'error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]' in C++?如何修复'错误:在 C++ 中从'int'到'const char *' [-fpermissive]'的无效转换?
【发布时间】: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

标签: c++ mysql++


【解决方案1】:

sprintf 返回一个表示

的 int

成功时,返回写入的字符总数。这 count 不自动包含额外的空字符 附加在字符串的末尾。失败时,负数是 返回。

& 不是您所期望的写入数据的 char 数组,所以基本上您应该这样做:

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());
mysqlpp::Query query 
                 = conn.query(buffer);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多