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

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

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

#include <iostream>
#include <mysql++.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
    mysqlpp::Connection conn(false);
    //connect to the database
    if(conn.connect("mysql_cpp_data", "127.0.0.1", "comoon", ""))
    {
        //build a template query
        mysqlpp::Query query = conn.query("select * from stock where item = %0q");
        query.parse();
        //get query result in a storeResult
        mysqlpp::StoreQueryResult res = query.store("Hotdog Buns");
        if(res)
        {
            cout << res[0]["item"] << endl;
            cout << res[0]["num"] << endl;
            cout << res[0]["price"] << endl;
        }
        else
        {
            perror("Failed to get data!");
            exit(EXIT_FAILURE);
        }
        query.reset();    //reset previous template query data
        query << "update stock set item = %0q where item = %1q";
        query.parse();
        mysqlpp::SimpleResult res1 = query.execute("abc", "Hotdog Buns");
    }
    else
    {
        perror("Connect Failed");
        exit(EXIT_FAILURE);
    }
    return 0;
}

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

建立一个模板查询

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

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

query.parse();

占位符的形式为:

扫描二维码关注公众号,回复: 4665174 查看本文章

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

猜你喜欢

转载自blog.csdn.net/cplus2009/article/details/82889272
今日推荐