我在尝试使用 C++ 和 MySQL C API 在 mysql 中获取表行时感到困惑.
I'm confused when trying to fetch table rows in mysql using C++ with MySQL C API.
我可以在 PHP 中轻松完成,只是因为 C++ 是一种强类型语言,因此我们还需要处理肮脏的过程..
I can do it easily in PHP, just because C++ is a strongly-typed language so that we also need to take care of the dirty process..
这就是我在 PHP 中的做法
This is how I done it in PHP
$data = array();
$i = 0;
$query = mysql_query("SELECT * FROM `my_table`");
while($fetch = mysql_fetch_array($query))
{
$data[$i] = $fetch['columntobefetched'];
$i++;
}
但是如何在 C++ 中用 MySQL API 做同样的事情?
But how to do the same in C++ with MySQL API?
到目前为止,这是我的代码......有一个令人困惑的死胡同......x__x
Here's my code so far....with a confusing dead end...x__x
MYSQL *sqlhnd = mysql_init(NULL);
mysql_real_connect(sqlhnd, "server", "user", "pass", "database", port, NULL, 0);
mysql_query(sqlhnd, "SELECT * FROM `my_table`");
MYSQL_RES *confres = mysql_store_result(sqlhnd);
int totalrows = mysql_num_rows(confres);
int numfields = mysql_num_fields(confres);
MYSQL_FIELD *mfield;
while((row = mysql_fetch_row(confres)))
{
for(i = 0; i < numfields; i++)
{
while(mfield = mysql_fetch_field(confres))
{
mfield->//??? I'm dead
}
}
}
基本上我想从数据库表中的一个字段中获取一个值并将其存储到一个变量中..
Basically I wanted to get a value from a field in the database table and store it to a variable..
任何形式的帮助将不胜感激:)
Any kind of help would be appreciated :)
谢谢
在 MySQL C API 中,mysql_fetch_row 返回一个 MYSQL_ROW 对象,它本质上是当前行中的值数组.
In the MySQL C API, mysql_fetch_row returns a MYSQL_ROW object, which is essentially an array of values in the current row.
因此,您的代码应该类似于:
So, your code should be something like:
mysql_query(sqlhnd, "SELECT * FROM `my_table`");
MYSQL_RES *confres = mysql_store_result(sqlhnd);
int totalrows = mysql_num_rows(confres);
int numfields = mysql_num_fields(confres);
MYSQL_FIELD *mfield;
while((row = mysql_fetch_row(confres)))
{
for(i = 0; i < numfields; i++)
{
char *val = row[i];
// do something with val...
}
}
最好不要在程序中执行SELECT * FROM mytable
".最好为您期望的字段命名,这样您就可以确定返回的字段的顺序.
Better yet, don't do a "SELECT * FROM mytable
" in a program. It would be much better to name the fields you expect, so that you can be sure of the order of the fields returned.
这篇关于使用 MySQL C API 和 C++ 获取 MySQL 数据库表中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!