语句执行
如执行查询页面所示,通过调用 mcosql_execute_query()
函数来执行 SQL 的 select 语句。然而,SQL 语句中的 insert、update、delete 和 create 则通过调用 mcosql_execute_statement()
函数来执行,如下例所示:
/* Add a Person record */
rs = mcosql_execute_statement(db, NULL, NULL,
"insert into Person (name,address,position,salary,rating,manager)
values (%s,%s,%s,%u,%f,%p)",
name, address, position, salary, rating, &manager_id );
/* Update the salary and rating for the record with the specified name */
rs = mcosql_execute_statement(db, NULL, &rc,
"update Person set salary=%u, rating=%f where name=%s",
salary, rating, name );
/* Delete all Person records */
rs = mcosql_execute_statement(db, NULL, NULL, "delete from Person" );
/* Create a table and a hash index */
rs = mcosql_execute_statement(db, NULL, NULL, "create table t1(s string, i integer)" );
rs = mcosql_execute_statement(db, NULL, NULL, "create unique index t1_pk on t1(i) using hash" );
请注意,在上述示例中,应用程序变量 name
、address
和 position
是字符字符串,salary
是无符号整数值,rating
是浮点值,&manager_id
是 int64_t 值的地址。
这些值会根据规则替换到 SQL 语句中,这些规则类似于标准 printf()
格式字符串的规则,在语句参数替换页面中有详细说明。
mcosql_execute_statement()
函数返回的值通过在头文件include/sql/sqlc.h中定义的返回码来指示成功或失败,并且它接受一个可变长度的参数列表,其中包括:
- db - 数据库引擎
- trans - 事务句柄,如果语句要在自动提交模式下执行,则为 NULL。
- n_records - 受影响的记录数(一个 int64_t 类型的值)
- statement - 要执行的 SQL 选择语句
- ... - 要插入到语句中的 0 个或多个参数列表。