Qt怎样创建数据库以及数据库的操作

时间:2022-02-14 10:57:11

qt可以实现连接各种数据库,这里介绍qt自带的一种数据库(Qsqlite)

#include<QSqlQuery>

#include<QObject>
#include<QVariantList>
#include<QDebug>
#include<QSqlError>
#include<QTextCodec>
#include<QObject>
 
staticboolcreateConnection()
{QSqlDatabasedb=QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("mytest.db");
if(!db.open())
returnfalse;
QSqlQueryquery;
//query.exec(QObject::tr("createtablestudent(idintprimarykey,namevchar)"));
//query.exec(QObject::tr("insertintostudentvalues(0,'刘')"));
////query.exec(QObject::tr("insertintostudentvalues(1,'刚')"));
//query.exec(QObject::tr("insertintostudentvalues(2,'红')"));
//query.prepare("insertintostudentvalues(?,?)");
//-------------------------------------------------------
//通过下面这段代码可以实现向数据库插入变量
//--------------------------------------------------------
QVariantListages;
intx1,x2,x3,x4;
x1=12;
x2=13;
x3=14;
x4=15;
ages<<x1<<x2<<x3<<x4;
query.addBindValue(ages);
QVariantListnames;
names<<QObject::tr("小王")<<QObject::tr("小明")<<QObject::tr("小张")<<QObject::tr("小新");//如果要提交空串,用QVariant(QVariant::String)代替名字
query.addBindValue(names);
if(!query.execBatch())//进行批处理,如果出错就输出错误
qDebug()<<query.lastError();
 
 
 
returntrue;
}
#endif//DATABASE_H
然后用QSqlTableModel实现数据库数据显示