C++類型安全SQL模版庫:sqlpp11
sqlpp11 是 C++ 的類型安全 SQL 模版庫。
sqlpp11 是一個嵌入式領域特定語言(EDSL)的代表模版庫:
-
為表和列定義類型
-
在編譯的時候檢查結構類型安全查詢(語法錯誤,類型錯誤,命名錯誤,甚至是一些語義錯誤)
-
通過迭代 query-specific 結構得到解析結果
示例
CREATE TABLE foo ( id bigint, name varchar(50), hasFun bool );假設有個數據庫連接對象:
TabFoo foo; Db db(/* some arguments*/); // selecting zero or more results, iterating over the results for (const auto& row : db(select(foo.name, foo.hasFun).from(foo).where(foo.id > 17 and foo.name.like("%bar%")))) { if (row.name.is_null()) std::cerr << "name is null, will convert to empty string" << std::endl; std::string name = row.name; // string-like fields are implicitly convertible to string bool hasFun = row.hasFun; // bool fields are implicitly convertible to bool } // selecting ALL columns of a table for (const auto& row : db(select(all_of(foo)).from(foo).where(foo.hasFun or foo.name == "joker"))) { int64_t id = row.id; // numeric fields are implicitly convertible to numeric c++ types } // selecting zero or one row, showing off with an alias: SQLPP_ALIAS_PROVIDER(cheese); if (const auto& row = db(select(foo.name.as(cheese)).from(foo).where(foo.id == 17))) { std::cerr << "found: " << row.cheese << std::endl; } // selecting a single row with a single result: return db(select(count(foo.id)).from(foo).where(true)).front().count; Of course there are joins and subqueries, more functions, order_by, group_by etc. These will be documented soon. // A sample insert db(insert_into(foo).set(foo.id = 17, foo.name = "bar", foo.hasFun = true)); // A sample update db(update(foo).set(foo.hasFun = not foo.hasFun).where(foo.name != "nobody")); // A sample delete db(remove_from(foo).where(not foo.hasFun));
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!