C++ , Vector & mysql
C++ , Vector & mysql
我从以下位置找到了此代码: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调用它(并重写代码的某些部分)。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- C++MySQL C api用户输入行
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 编译器如何区分std::vector的构造函数
- 将 int 数组转换为 std::vector<int*>
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 使用mysql c++连接器的未定义引用
- 在std::vector上存储带有模板的类实例
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 为什么std::vector比数组慢
- C++ , Vector & mysql