Qt数据库SQL语句绑定方式与插入空值

Approaches to Binding Values
Below we present the same example using each of the four different binding approaches, as well as one example of binding values to a stored procedure.


Named binding using named placeholders :
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname)VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");

query.exec();


Positional binding using named placeholders :
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname)VALUES (:id, :forename, :surname)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");

query.bindValue(2, "Simpson");

query.exec();


Binding values using positional placeholders(version 1) :
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname)VALUES (?, ?, ?)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");

query.exec();


Binding values using positional placeholders(version 2) :
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname)VALUES (?, ?, ?)");
query.addBindValue(1001);
query.addBindValue("Bart");
query.addBindValue("Simpson");

query.exec();


Binding values to a stored procedure :
This code calls a stored procedure called AsciiToInt(), passing it a character through its in parameter, and taking its result in the out parameter.

QSqlQuery query;
query.prepare("CALL AsciiToInt(?, ?)");
query.bindValue(0, "A");
query.bindValue(1, 0, QSql::Out);
query.exec();

int i = query.boundValue(1).toInt(); // i is 65

Note that unbound parameters will retain their values.


Stored procedures that uses the return statement to return values, or return multiple result sets, are not fully supported.For specific details see SQL Database Drivers.


To bind NULL values, a null QVariant of the relevant type has to be added to the bound QVariantList; for example,QVariant(QVariant::String) should be used if you are using strings.

QSqlQuery q;
q.prepare("insert into myTable values (?, ?)");
QVariantList ints;
ints << 1 << 2 << 3 << QVariant(QVariant::Int);
q.addBindValue(ints);
QVariantList names;
names << "Harald" << "Boris" << "Trond" << QVariant(QVariant::String);
q.addBindValue(names);
if (!q.execBatch())
qDebug() << q.lastError();

The example above inserts four new rows into myTable :
1         Harald
2         Boris
3         Trond
NULL  NULL

Warning: You must load the SQL driver and open the connection before a QSqlQuery is created.Also, the connection must remain open while the query exists; otherwise, the behavior ofQSqlQuery is undefined.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值