Mysql++学习(四)------模板查询

MySQL++提供的另外一个强大的功能就是模板查询,它提供像c语言中printf类似的机制:你提供给MySQL++一个包含固定串和变量占位符的查询字符串,之后可以替换这些占位符的变量.

下面例子显示了如何使用这一特性

 1 #include <iostream>
 2 #include <mysql++.h>
 3 #include <errno.h>
 4 #include <stdlib.h>
 5 #include <stdio.h>
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11     mysqlpp::Connection conn(false);
12     //connect to the database
13     if(conn.connect("mysql_cpp_data", "127.0.0.1", "comoon", ""))
14     {
15         //build a template query
16         mysqlpp::Query query = conn.query("select * from stock where item = %0q");
17         query.parse();
18         //get query result in a storeResult
19         mysqlpp::StoreQueryResult res = query.store("Hotdog Buns");
20         if(res)
21         {
22             cout << res[0]["item"] << endl;
23             cout << res[0]["num"] << endl;
24             cout << res[0]["price"] << endl;
25         }
26         else
27         {
28             perror("Failed to get data!");
29             exit(EXIT_FAILURE);
30         }
31         query.reset();    //reset previous template query data
32         query << "update stock set item = %0q where item = %1q";
33         query.parse();
34         mysqlpp::SimpleResult res1 = query.execute("abc", "Hotdog Buns");
35     }
36     else
37     {
38         perror("Connect Failed");
39         exit(EXIT_FAILURE);
40     }
41     return 0;
42 }

query.parse()之前的代码用于设置模板,parse()调用用于使其生效,自生效开始,你可以通过调用查询的多个函数来多次使用这个模板

建立一个模板查询

建立一个模板查询,首先你得把内容插入到查询对象中,用数字来表示要替换的占位符,然后调用parse() 函数,告诉查询对象,这是一个查询模板,需要被解析

query << "select (%2:field1, %3:field2) from stock where %1:wheref = %0q:what";
query.parse();

占位符的形式为:

%###(modifier)(:name)(:)

“###” 为最大三位的数字,表示给SQLQueryParms对象的参数序列,从0开始

modifier可以是下面任意一个:

%打印一个实际的“%”符号

“”不管什么,都不要引号或者忽略

q将被用单引号括起来,不被作为关键字解释

Q将被用引号括起来,不过不会避免关键字检测

设置参数

在查询的时候,你需要指定参数.“parm0”对应于第一个参数,依次类推.

例如:

StoreQueryResult res = query.store("Dinner Rolls", "item", "item", "price")

上面的查询将会被解析为:

select (item, price) from stock where item = "Dinner Rolls"

默认参数

模板查询机制,允许你设置默认参数.你只需要给Query::template_defaultsarray对应元素赋值就可以了

query.template_defaults[1] = "item";
query.template_defaults["wheref"] = "item";

这种默认参数机制类似C++的函数默认参数.

原文地址:https://www.cnblogs.com/comoon/p/4124871.html