mysql实验8模板_Mysql++学习(四)------模板查询

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

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

1 #include

2 #include

3 #include

4 #include

5 #include

6

7 using namespacestd;8

9 intmain()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"] <

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++的函数默认参数.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值