我有以下代码来设置默认值:
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?
答案 0 :(得分:0)
应该在单一准备中抛出 - 其余部分永远不应该被执行。
准备好的陈述不会以这种方式运作。
它们不是字符串替换。
预准备语句中的参数仅用于数据值 - 不是对象标识符或SQL语句的任何其他部分。只是数据值。
例如,您无法准备语句SELECT ? FROM ?
并使用参数&#34; id&#34;和&#34; table1&#34;好像你查询了SELECT id FROM table1;
。 SQL - 在任何数据库引擎中 - 都不允许这样做。
首先解析预处理语句,然后在执行语句时使用值 - 而不是字符串插值。