mysql 数据库编程_MySQL数据库编程(C++语言)
MySQL數(shù)據(jù)庫(kù)編程(C++語(yǔ)言)
發(fā)布時(shí)間:2018-05-24 21:06,
瀏覽次數(shù):452
, 標(biāo)簽:
MySQL
本文主要介紹使用C++語(yǔ)言連接和操作 MySQL 數(shù)據(jù)庫(kù)的方法。
1. 準(zhǔn)備
本文利用 MySQL++ 接口進(jìn)行C++語(yǔ)言的數(shù)據(jù)庫(kù)編程。
MySQL++ 的官網(wǎng)定義如下:
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
同時(shí),MySQL++ 需要用到 MySQL devel 的文件,所以也需要安裝 mysql-devel,如下:
yum install mysql-community-devel.x86_64 -y
說(shuō)明:關(guān)于 MySQL(mysql-community-*) 相關(guān)文件的安裝,請(qǐng)點(diǎn)擊此處
。
2. 編寫C++程序
我們本次編寫一個(gè)簡(jiǎn)單的連接、操作數(shù)據(jù)庫(kù)的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 = ""; // 創(chuàng)建數(shù)據(jù)庫(kù)連接 mysqlpp::Connection
conn(false); // 連接數(shù)據(jù)庫(kù) if (conn.connect(db, server, user, password)) { cout <<
"connect db succeed." << endl; // 查詢操作,查詢結(jié)果保存在 query 中 mysqlpp::Query query =
conn.query("SELECT * FROM roles"); // 處理并打印查詢結(jié)果 if (mysqlpp::StoreQueryResult
res = query.store()) { // 輸出數(shù)據(jù)左對(duì)齊 cout.setf(ios::left); // 字段寬度為20位 // 打印表的字段名
cout << setw(21) << "role_id" << setw(21) << "occupation" << setw(21) << "camp"
<< endl; // 打印查詢結(jié)果 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; }
編譯生成可執(zhí)行程序,如下:
g++ -o mysql_test mysql_test.cpp -I/usr/include/mysql++/ -I/usr/include/mysql/
-lmysqlpp
3. 測(cè)試
本次編寫的代碼連接的數(shù)據(jù)庫(kù)位于 192.168.213.130 服務(wù)器上,相關(guān)的數(shù)據(jù)庫(kù)信息參考源代碼內(nèi)容。
運(yùn)行上面編譯生成的程序,如下:
上述結(jié)果表明,我們編寫的程序 mysql_test 成功地執(zhí)行了連接、查詢數(shù)據(jù)庫(kù)操作。
總結(jié)
以上是生活随笔為你收集整理的mysql 数据库编程_MySQL数据库编程(C++语言)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: css设置title字体_CSS中简写属
- 下一篇: 关于mysql优化_MYSQL---关于