#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实现数据库数据显示
Qt默认是支持QSQLITE数中困据库的QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE") db.setHostName("acidalia") db.setDatabaseName("customdb") db.setUserName("mojito"纯培迅做此) db.setPassword("J0a1m8") bool ok = db.open()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)