QT 连接SQLLite的代码
时间: 2024-05-11 11:15:50 浏览: 104
请见下方示例代码:
```cpp
#include <QCoreApplication>
#include <QtSql>
int main()
{
// 连接数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test.db");
if (!db.open())
{
qDebug() << "Failed to connect to database.";
return -1;
}
// 创建表
QSqlQuery query;
if(query.exec("CREATE TABLE t_person (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"))
{
qDebug() << "Create table success.";
}
else
{
qDebug() << "Failed to create table.";
return -1;
}
// 添加数据
QString name = "Tom";
int age = 20;
if (query.prepare("INSERT INTO t_person(name, age) VALUES(:name,:age)"))
{
query.bindValue(":name", name);
query.bindValue(":age", age);
if (query.exec())
{
qDebug() << "Insert data success.";
}
else
{
qDebug() << "Failed to insert data.";
return -1;
}
}
else
{
qDebug() << "Failed to prepare insert data.";
return -1;
}
// 查询数据
if (query.exec("SELECT id, name, age FROM t_person"))
{
while (query.next())
{
int id = query.value(0).toInt();
QString name = query.value(1).toString();
int age = query.value(2).toInt();
qDebug() << "id=" << id << ", name=" << name << ", age=" << age;
}
}
else
{
qDebug() << "Failed to select data.";
return -1;
}
// 关闭数据库
db.close();
return 0;
}
```
以上示例代码包括了连接数据库、创建表、添加数据以及查询数据的过程,请根据具体情况进行相应修改。
阅读全文