向MySQL ++查询添加字符串

时间:2013-02-17 20:49:01

标签: c++ mysql mysql++

我正在尝试MySQL++并正在调查查询。我希望能够将字符串变量插入到我的查询中,所以像这样:

query << "CREATE TABLE beer (" 
      << "beerID smallint(3) unsigned NOT NULL AUTO_INCREMENT,"
      << "beerName varchar(30) NOT NULL,"
      << "PRIMARY KEY (beerID));";

可能是这样的:

query << "CREATE TABLE " << tableName << " (" 
      << fieldName1 << " smallint(3) unsigned NOT NULL AUTO_INCREMENT,"
      << fieldName2 << " varchar(30) NOT NULL,"
      << "PRIMARY KEY (" << fieldName1 << "));";

其中 tableName fieldName1 fieldName2 都是某些类型的字符串变量,可以在运行时修改,以便用户可以定义应用程序运行时的表和字段名称(以及后来的表数据)。这样的事情可能吗?如果是这样,怎么样?我看到的文档对此并不十分清楚,我使用C ++字符串没有取得任何成功。

2 个答案:

答案 0 :(得分:0)

  

我没有使用c ++字符串取得任何成功。

您没有显示尝试时遇到的错误。

我刚刚修改了examples/resetdb.cpp,以便做你正在尝试的事情:

--- examples/resetdb.cpp    (revision 2716)
+++ examples/resetdb.cpp    (working copy)
@@ -132,14 +132,17 @@
        // Send the query to create the stock table and execute it.
        cout << "Creating stock table..." << endl;
        mysqlpp::Query query = con.query();
+       string table_name("stock");
+       string f1("item"), f2("num"), f3("weight"), f4("price"),
+               f5("sdate"), f6("description");
        query <<
-               "CREATE TABLE stock (" <<
-               "  item CHAR(30) NOT NULL, " <<
-               "  num BIGINT NOT NULL, " <<
-               "  weight DOUBLE NOT NULL, " <<
-               "  price DECIMAL(6,2) NULL, " << // NaN & inf. == NULL
-               "  sdate DATE NOT NULL, " <<
-               "  description MEDIUMTEXT NULL) " <<
+               "CREATE TABLE " << table_name << " (" <<
+               f1 << " CHAR(30) NOT NULL, " <<
+               f2 << " BIGINT NOT NULL, " <<
+               f3 << " DOUBLE NOT NULL, " <<
+               f4 << " DECIMAL(6,2) NULL, " << // NaN & inf. == NULL
+               f5 << " DATE NOT NULL, " <<
+               f6 << " MEDIUMTEXT NULL) " <<
                "ENGINE = InnoDB " <<
                "CHARACTER SET utf8 COLLATE utf8_general_ci";
        query.execute();

我使用这些更改重建了MySQL ++,重新运行了自我测试套件,它提供了与以前完全相同的测试结果。如果表结构已经发生了变化,我预计很多测试都会失败。

所以,你必须做其他事情,但我无法猜出你的问题是什么。

答案 1 :(得分:-1)

您应该查看http://tangentsoft.net/mysql++/doc/html/userman/tutorial.html#qescape

E.g。生产:

SELECT * FROM stock WHERE item = 'Hotdog Buns'

您可以使用:

string s = "Hotdog Buns";
query << "SELECT * FROM stock WHERE item = " << quote_only << s;