linux下C++訪問mysql數據庫
這篇雖然是C++ 的語句,但因為只是練習,圖方便就用C風格的方式寫了
#include <mysql/mysql.h>
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
MYSQL *connection;
MYSQL_RES *result;
MYSQL_ROW row;
connection = mysql_init(NULL);
if(connection == NULL)
{
std::cout << "error:" << mysql_error(connection);
exit(1); // exit(1)表示發生錯誤后退出程序, exit(0)表示正常退出
}
connection = mysql_real_connect(connection, "localhost", "root", "wei123", "wei",0, NULL, 0); // 建立數據庫連接
if(connection == NULL)
{
std::cout << "error:" << mysql_error(connection);
exit(1); // exit(1)表示發生錯誤后退出程序, exit(0)表示正常退出
}
//查詢
std::string sql = "select * from user";
mysql_real_query(connection, sql.c_str(), sql.length());
result = mysql_use_result(connection); // 獲取結果集
// mysql_field_count()返回connection查詢的列數
for(int i=0; i < mysql_field_count(connection); ++i)
{
// 獲取下一行
row = mysql_fetch_row(result);
if(row <= 0)
{
break;
}
// mysql_num_fields()返回結果集中的字段數
for(int j=0; j < mysql_num_fields(result); ++j)
{
std::cout << row[j] << " ";
}
std::cout << std::endl;
}
mysql_free_result(result);
mysql_close(connection);
return 0;
}
要安裝mysql-server、mysql-client、devel.
編譯語句:g++ text.cpp -o text -lmysqlclient
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!