duckdb c++如何进行sqlt参数化查询请举例
在DuckDB C++中进行SQL参数化查询的方式是使用预处理语句和参数占位符。以下是一个简单的例子:
#include "duckdb.hpp"
#include <iostream>
using namespace duckdb;
using namespace std;
int main() {
DuckDB db("");
// create table
db.Query("CREATE TABLE test(id INTEGER, name VARCHAR)");
// prepare statement with parameter
PreparedStatement statement(db, "INSERT INTO test VALUES (?, ?)");
// bind parameters
statement.Bind<int32_t>(0, 1);
statement.Bind<const char *>(1, "John");
// execute statement
statement.Execute();
// prepare statement with parameter
PreparedStatement select_statement(db, "SELECT * FROM test WHERE id = ?");
// bind parameter
select_statement.Bind<int32_t>(0, 1);
// execute statement and print result
auto result = select_statement.Execute();
while (result->Fetch()) {
cout << "id: " << result->GetValue<int32_t>(0) << ", name: " << result->GetValue<string>(1) << endl;
}
return 0;
}
在这个例子中,我们首先创建了一个名为test的表格。然后,我们准备了一个带参数的插入语句,使用问号作为参数占位符。我们绑定了两个参数值:id为1,name为"John"。然后我们执行了该语句。
接下来,我们准备了一个带参数的选择语句,使用问号作为参数占位符。我们只绑定了一个参数值:id为1。我们执行该语句,并打印结果。
在这个例子中,我们使用了PreparedStatement类来准备SQL语句并绑定参数。它还提供了其他常用的功能,如批量插入
原文地址: https://www.cveoy.top/t/topic/cStE 著作权归作者所有。请勿转载和采集!