0

我正在尝试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 << "));";

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

4

2 回答 2

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++,重新运行了它的自测套件,它给出了与以前完全相同的测试结果。如果表结构发生了变化,我预计许多测试都会失败。

因此,您必须在做其他事情,但我无法从您的问题中猜出是什么。

于 2013-02-19T01:33:15.357 回答
-1

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

例如生产:

SELECT * FROM stock WHERE item = 'Hotdog Buns'

您可以使用 :

string s = "Hotdog Buns";
query << "SELECT * FROM stock WHERE item = " << quote_only << s;
于 2013-02-17T20:55:58.673 回答