创建数据库:
QSqlDatabase database;
database = QSqlDatabase::addDatabase("QSQLITE", CONNECTION_NAME);
database.setDatabaseName("D:\test.db"); //不指示路径的话,数据库不会生成到想去的地方
if (!database.open())
{
qDebug() << "Error: Failed to connect database." << database.lastError();
}
else
{
qDebug() << "Succeed to connect database.";
}
创建表:
auto _db = QSqlDatabase::database(CONNECTION_NAME);
QSqlQuery query(_db);
query.exec(QString("select count(*) from sqlite_master where type='table' and name='%1'").arg("tableName"));
if (query.next())
{
if (query.value(0).toInt() == 0)
{
// 表不存在
QSqlQuery _query(_db);
bool _ok = _query.exec("CREATE TABLE IF NOT EXISTS tableName (...)");
if (!_ok)
{
return false;
}
return true;
}
else {
//表存在,清空表数据
bool _ok = query.exec("delete from tableName");
query.clear();
return _ok;
}
}
}