日期:2014-05-16 浏览次数:20955 次
#include <iostream> #include <windows.h> #include <mysql.h> #include <string> static const char host[32] = "localhost"; static const char user[32] = "test"; static const char passwd[32] = "********"; static const char db[32] = "test"; // // Just for demo only. // int main() { MYSQL* mysql_ = NULL; MYSQL_RES* result_ = NULL; MYSQL_ROW row_; mysql_ = mysql_init(mysql_); if (mysql_real_connect(mysql_, host, user, passwd, db, 3306, NULL, 0) == NULL) { const char * error = mysql_error(mysql_); std::cout<<"*** Connection Error " << error << std::endl; return -1; } mysql_autocommit(mysql_, false); std::string encodeStr = "set names 'gbk'"; mysql_real_query(mysql_, encodeStr.c_str(), encodeStr.size()); const char* tmpTableName = "t"; // assume you are querying the table 't' char str[512]; int cnt = 0; sprintf(str,"select count(*) as cnt from %s", tmpTableName); mysql_real_query(mysql_, str, strlen(str)); result_ = mysql_store_result(mysql_); while (row_ = mysql_fetch_row(result_)) { // get the field value if (row_[0]) { std::cout<<"count = "<<row_[0]<<std::endl; // convert it into int cnt = atoi(row_[0]); std::cout<<"cnt value = "<<row_[0]<<std::endl; } } mysql_free_result(result_); mysql_close(mysql_); return 0; }