C++ , Vector & mysql

C++ , Vector & mysql

本文关键字:mysql Vector C++      更新时间:2023-10-16

我从以下位置找到了此代码:http://www.davenicholas.me.uk/blog/view_post/29/How-to-c-mysql-mac-osx

#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#include <string>
#include <vector>
int main()
{
    std::vector<std::string> tables;
    MYSQL_RES *result;
    MYSQL_ROW row;
    MYSQL *connection, mysql;
    int state;
    connection = mysql_real_connect(&mysql,"localhost","username","password","database",0,0,0);
    if (connection == NULL)
    {
        std::cout << mysql_error(&mysql) << std::endl;
        return tables;
    }
    state = mysql_query(connection, "SHOW TABLES");
    if (state !=0)
    {
        std::cout << mysql_error(connection) << std::endl;
        return tables;
    }
    result = mysql_store_result(connection);
    std::cout << "tables: " << mysql_num_rows(result) << std::endl;
    while ( ( row=mysql_fetch_row(result)) != NULL )
    {
        tables.push_back(row[0]);
    }
    mysql_free_result(result);
    mysql_close(connection);
        return 0;
}

但当我构建它时,我得到了错误:

error: cannot convert 'std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >' to 'int' in return

error: cannot convert 'std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >' to 'int' in return

我认为问题可能是在连接或查询调用失败时执行return tables;。这意味着您从main()返回std::vector,而main()应该返回int

我认为这段代码应该在另一个函数中,绝对不是在main()中。

将此代码移动到返回std::vector<std::string>的函数中,并从main():调用该函数

std::vector<std::string> get_tables()
{
    std::vector<std::string> tables;
    MYSQL_RES *result;
    MYSQL_ROW row;
    MYSQL *connection, mysql;
    int state;
    connection = mysql_real_connect(&mysql,"localhost","username","password","database",0,0,0);
    ...
    return tables;
}
int main()
{
    std::vector<std::string> tables = get_tables();
    // do something useful with `tables'
    return 0;
}

这是因为table变量被定义为vector,但它作为函数的返回值返回;但是该函数被声明为具有CCD_ 10作为返回值。解决这个问题的最好方法是将处理table的部分移到另一个函数,并从main调用它(并重写代码的某些部分)。