3

我遇到了 QSqlRecord 的一个奇怪问题,它插入 null 而不是 '0'。这是说明问题的示例代码:

#include <QCoreApplication>
#include <QtSql>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

// Filename for sqlite database
QString filename = "./test.db";

// Make sure the database doesn't already exisit
if (QFile::exists(filename)){
    QFile::remove(filename);
}

// Connect to the database
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(filename);

db.open();

// Create test table
QSqlQuery query(db);

bool result;
result = query.exec("CREATE TABLE IF NOT EXISTS 'test' ('key' TEXT, 'value' INTEGER)");
db.commit();
// Insert the test value into the database
QSqlTableModel model(0, db);

// Set the table
model.setTable("test");

// Set up the data
QSqlRecord record = model.record();
record.setValue("key", "first");
record.setValue("value", 1);
result = model.insertRecord(-1, record);
model.submitAll();

record.setValue("key", "second");
record.setValue("value", 0);
result = model.insertRecord(-1, record);
model.submitAll();

record.setValue("key", "third");
record.setValue("value", 2);
result = model.insertRecord(-1, record);
model.submitAll();
// Commit changes and close database]
db.commit();
db.close();
}

如果我查询test.db我得到:

sqlite> select * from test;
first|1
second|
third|2

请注意,第二个条目没有值。

我在 Windows 7 上使用 Qt 5.0.1 和 Mingw 4.7。

4

0 回答 0