qt读取sql数据代码

#include “mainwindow.h”
#include “ui_mainwindow.h”

#include
#include
#include
#include <qdebug.h>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//建立并打开数据库
QSqlDatabase database;
database = QSqlDatabase::addDatabase(“QSQLITE”);
database.setDatabaseName(“test.db”);
if (!database.open())
{
qDebug() << “Error: Failed to connect database.” << database.lastError();
}
else
{
qDebug() << “Succeed to connect database.” ;
}

//创建表格
QSqlQuery sql_query;
if(!sql_query.exec("create table student(id int primary key, name text, age int)"))
{
    qDebug() << "Error: Fail to create table."<< sql_query.lastError();
}
else
{
    qDebug() << "Table created!";
}

//插入数据
if(!sql_query.exec("INSERT INTO student VALUES(1, \"Wang\", 23)"))
{
    qDebug() << sql_query.lastError();
}
else
{
    qDebug() << "inserted Wang!";
}
if(!sql_query.exec("INSERT INTO student VALUES(2, \"Li\", 23)"))
{
    qDebug() << sql_query.lastError();
}
else
{
    qDebug() << "inserted Li!";
}

//修改数据
sql_query.exec("update student set name = \"QT\" where id = 1");
if(!sql_query.exec())
{
    qDebug() << sql_query.lastError();
}
else
{
    qDebug() << "updated!";
}

//查询数据
sql_query.exec("select * from student");
if(!sql_query.exec())
{
    qDebug()<<sql_query.lastError();
}
else
{
    while(sql_query.next())
    {
        int id = sql_query.value(0).toInt();
        QString name = sql_query.value(1).toString();
        int age = sql_query.value(2).toInt();
        qDebug()<<QString("id:%1    name:%2    age:%3").arg(id).arg(name).arg(age);
    }
}

//删除数据
sql_query.exec("delete from student where id = 1");
if(!sql_query.exec())
{
    qDebug()<<sql_query.lastError();
}
else
{
    qDebug()<<"deleted!";
}

//删除表格
sql_query.exec("drop table student");
if(sql_query.exec())
{
    qDebug() << sql_query.lastError();
}
else
{
    qDebug() << "table cleared";
}

//关闭数据库
database.close();

}

MainWindow::~MainWindow()
{
delete ui;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值