mysql++ 內建的一些精巧示範例子

來源:互聯網
上載者:User

最近在工作的時候需要使用 mysql++ 來訪問 MySQL 資料庫,下載源碼後看了一下,發現一些代碼 非常優雅。
所以貼出來,和大家分享一下。

簡單介紹一下 mysql++

mysql++ API 是一組訪問MySQL的C++ API封裝。主要目的在於把各種Query的操作和STL容器更好的結合。
mysql++ 可以在這裡下載: http://www.mysql.com/download_mysql++.html
mysql++ 的郵件清單是: mysql-plusplus@lists.mysql.com
mysql++ API 的幾個典型例子:

使用 in 刪除 記錄:

  ostringstream strbuf;
  unsigned int i = 0;
  con.real_connect(MY_DATABASE, MY_HOST, MY_USER, MY_PASSWORD, 3306, (int) 0, 60, NULL);
  Query query = con.query();
  query << MY_QUERY;       // 使用這樣的方法進行查詢,真是很簡練呀!tcf
  ResUse res = query.use();
  Row row;
  // 開始拼 sql
  strbuf << "delete from " << MY_TABLE << " where " << MY_FIELD << " in (";
  for (; row = res.fetch_row(); i++)
   strbuf << row[0] << ",";
  if (!i)
   return 0;
  string output(strbuf.str());
  output.erase(output.size() - 1, 1); // 去掉最後一個,
  output += ")";
  query.exec((const string &) output); 
  //列印結果
  cout << output << endl;
  return 0;

-------------------------------------------------------------------------------------------------------
 query.reset();
 query << "select * from cpptest";
 // 列印 query 語句
 cout << "Query: " << query.preview() << endl;

 // 執行query 並儲存到 Result
 mysqlpp::Result res = query.store();
 cout << "記錄條數: " << res.size() << endl << endl;
 // 列印表中的資料
 cout.setf(ios::left);
 cout << setw(20) << "Item" <<
  setw(9) << "Num" <<
  setw(9) << "Weight" <<
  setw(9) << "Price" << "Date" << endl << endl;

 // Result 類提供的 iterator是唯讀隨機 顯示讀取記錄的
 mysqlpp::Row row;
 mysqlpp::Result::iterator i;
 
 for (i = res.begin(); i != res.end(); ++i) {
  row = *i;
  // 可以使用 列的位置或者 名稱來 顯示
  cout << setw(20) << row[0].c_str() <<
   setw(9) << row[1].c_str() <<
   setw(9) << row.lookup_by_name("weight").c_str() <<
   setw(9) << row[3].c_str() <<
   row[4] << endl;
 }

-----------------------------------------------------------------------------------------------------

一個簡單的查詢
  Query query = con.query();
  stock row;
  row.set("Hot Dogs", 100, 1.5, 1.75, "1998-09-25");
  query.insert(row);
  cout << "Query : " << query.preview() << endl;
  query.execute();
  print_stock_table(query);
--------------------------------------------------------------------------------------------------------

我現在要做的是 在 ATL 中使用 mysql++ 。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.