mysql 数据库编程_MySQL数据库编程(C++语言)
MySQL數據庫編程(C++語言)
發布時間:2018-05-24 21:06,
瀏覽次數:452
, 標簽:
MySQL
本文主要介紹使用C++語言連接和操作 MySQL 數據庫的方法。
1. 準備
本文利用 MySQL++ 接口進行C++語言的數據庫編程。
MySQL++ 的官網定義如下:
MySQL++ is a C++ wrapper for MySQL’s C API. It is built around the same
principles as the Standard C++ Library, to make dealing with the database as
easy as dealing with STL containers. In addition, MySQL++ provides facilities
that let you avoid the most repetitive sorts of SQL within your own code,
providing native C++ interfaces for these common tasks.
為了使用 MySQL++ 接口編寫C++程序,首先需要安裝 MySQL++ ,本文使用 yum 命令安裝 MySQL++ ,如下:
yum install mysql++-devel.x86_64 mysql++.x86_64 -y
同時,MySQL++ 需要用到 MySQL devel 的文件,所以也需要安裝 mysql-devel,如下:
yum install mysql-community-devel.x86_64 -y
說明:關于 MySQL(mysql-community-*) 相關文件的安裝,請點擊此處
。
2. 編寫C++程序
我們本次編寫一個簡單的連接、操作數據庫的C++程序,代碼(mysql_test.cpp)如下:
#include #include "mysql++.h" using namespace std; int main() {
const char* db = "testdb"; const char* server = "192.168.213.130"; const char*
user = "root"; const char* password = ""; // 創建數據庫連接 mysqlpp::Connection
conn(false); // 連接數據庫 if (conn.connect(db, server, user, password)) { cout <<
"connect db succeed." << endl; // 查詢操作,查詢結果保存在 query 中 mysqlpp::Query query =
conn.query("SELECT * FROM roles"); // 處理并打印查詢結果 if (mysqlpp::StoreQueryResult
res = query.store()) { // 輸出數據左對齊 cout.setf(ios::left); // 字段寬度為20位 // 打印表的字段名
cout << setw(21) << "role_id" << setw(21) << "occupation" << setw(21) << "camp"
<< endl; // 打印查詢結果 mysqlpp::StoreQueryResult::const_iterator it; for (it =
res.begin(); it != res.end(); ++it) { mysqlpp::Row row = *it; cout << setw(20)
<< row[0] << ' ' << setw(20) << row[1] << ' ' << setw(20) << row[2] << ' ' <<
endl; } } } else { cout << "connect db fail." << endl; } return 0; }
編譯生成可執行程序,如下:
g++ -o mysql_test mysql_test.cpp -I/usr/include/mysql++/ -I/usr/include/mysql/
-lmysqlpp
3. 測試
本次編寫的代碼連接的數據庫位于 192.168.213.130 服務器上,相關的數據庫信息參考源代碼內容。
運行上面編譯生成的程序,如下:
上述結果表明,我們編寫的程序 mysql_test 成功地執行了連接、查詢數據庫操作。
總結
以上是生活随笔為你收集整理的mysql 数据库编程_MySQL数据库编程(C++语言)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css设置title字体_CSS中简写属
- 下一篇: 关于mysql优化_MYSQL---关于