1

我有以下代码来设置默认值:

int main()
{
    try 
    {
        sql::Driver *driver;
        sql::Connection *con;
        sql::PreparedStatement *pstmt;

        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "$user", "$password");
        /* Connect to the MySQL test database */
        con->setSchema("db");

        string cols[] = { "email", "phone", "first_lead", "address", "city", "state", "country", "client_id" };
        string filler[] = { "email_address@email.com","7777777777", "YYYY-MM-DD", "street_address", "city", "state", "country", "client_id" };

        pstmt = con->prepareStatement("ALTER table clients modify column ? varchar(255) not null default \'?\'");

        for (int i = 0; i <= 8; ++i)
        {
            pstmt->setString(1, cols[i].c_str());
            pstmt->setString(2, filler[i].c_str());
            pstmt->execute();
        }
        delete pstmt;
        delete con;
    } catch (sql::SQLException &e) 
    {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line "
            << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() <<
            " )" << endl;
    }

    cout << endl;
    system("pause");
    return EXIT_SUCCESS;
}

当我运行代码时,它会命中 pstmt 分配并返回以下错误:

# ERR: SQLException in c:\users\ray\documents\visual studio 2015\projects\project3\project3\source.cpp(main) on line 56
# ERR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? varchar(255) not null default '?'' at line 1 (MySQL error code: 1064, SQLState:  ?Σ╥Å  ╠╠╠╠╠╠╠ )

该代码似乎无法识别和替换占位符。我是否错误地实现了 setString?

4

1 回答 1

1

应该在单元准备时抛出异常——其余的永远不应该被执行。

准备好的语句不能以这种方式工作。

它们不是字符串替换。

准备好的语句中的参数仅用于数据值——而不是对象标识符或 SQL 语句的任何其他部分。只是数据值。

例如,您不能SELECT ? FROM ?像查询SELECT id FROM table1;. SQL——在任何数据库引擎中——都不允许这样做。

首先解析准备好的语句,然后在执行语句时使用值——不是字符串插值。

于 2017-06-16T04:13:34.493 回答