gpt4 book ai didi

C++ mysql setString 不替换准备好的语句中的占位符

转载 作者:行者123 更新时间:2023-11-29 18:46:54 28 4
gpt4 key购买 nike

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

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?

最佳答案

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

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

它们不是字符串替换。

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

例如,您不能准备语句 SELECT 吗? FROM ? 并使用参数“id”和“table1”,就像查询SELECT id FROM table1;一样。 SQL——在任何数据库引擎中——都不允许这样做。

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

关于C++ mysql setString 不替换准备好的语句中的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44557635/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com