我需要编写一个包装器(基于MySQL Connector/C++)来封装特定的SQL语句并提供用户友好的界面,例如:insert() 、update()、delete()、select()等
在 MySQL 的 native C API 中,每个 SQL 语句都可以通过简单地调用 "mysql_real_query()" 来执行,但是现在,在 MySQL Connector/C++ 中,事情变得有点困惑。 sql::Statment类中有3个执行函数,sql::PreparedStatement类中有6个执行函数:
mysql-connector-c++-1.1.5\driver\mysql_statement.h:
bool execute(const sql::SQLString& sql);
sql::ResultSet* executeQuery(const sql::SQLString& sql);
int executeUpdate(const sql::SQLString& sql);
mysql-connector-c++-1.1.5\driver\mysql_prepared_statement.h, 104:
bool execute();
bool execute(const sql::SQLString& sql);
sql::ResultSet executeQuery();
sql::ResultSet executeQuery(const sql::SQLString& sql);
int executeUpdate();
int executeUpdate(const sql::SQLString& sql);
我想知道为什么有这么多的执行函数而不是一个简单统一的? 我应该使用哪个执行函数来指定 SQL 语句?
注意:我正在使用 MySQL Connector/C++ 1.1.5 和 MySQL Server 5.6 作为后端。
最佳答案
这三个函数各有用途,从返回类型就可以猜到。
执行
这个函数是最通用的。它返回一个 bool 值,如果查询返回多个结果,则该值为 true,如果查询不返回任何内容或返回更新计数,则该值为 false。
如果您只想使用一个尽可能通用的函数,那么这就是您要使用的函数。
如果它返回 true,您将需要使用 ResultSet * getResultSet()
来获取结果。
如果它返回 false,您将需要使用 uint64_t getUpdateCount()
获取更新的行数。
执行查询
该函数直接返回一个ResultSet
,用于SELECT
语句,并假设确实有一个结果集要返回。
相当于调用 execute()
后跟 getResultSet()
。
当您知道您正在使用返回行等结果的 SQL 代码时,您会想要使用此函数。
执行更新
此函数返回一个对 UPDATE
语句有用的整数值,并假设有一个更新计数要返回。
它等效于调用 execute()
,然后调用 getUpdateCount()
,尽管由于某种原因,返回类型不同(int 与 uint64_t)。
这是执行修改数据的SQL语句时使用的函数,您需要知道某些数据是否被修改。
所以,
why there're so many execution functions rather than a simple and unified one?
统一的实际上是execute
,它可以用来执行任意SQL并适本地处理结果,而另外两个是方便的包装器,当你知道你执行什么样的查询时。
which execute function should i use for specify SQL statements?
在您的情况下,由于您正在围绕 SQL 语言编写包装器,因此您的每个函数都知道它将执行哪种语句,因此使用便利函数将使您能够编写更短的代码。
例如:
insert(), update(), delete() ---> executeUpdate()
select() ---> executeQuery()
关于c++ - 我应该在 MySQL connector/c++ 中使用哪个执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27480741/