問題描述
我在嘗試使用 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模板網!