一、连接数据库
QSqlDatabase db;
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("sqltest.db");
db.setUserName("xupeng");
db.setPassword("xupeng1992");
if(db.open())
{
qDebug()<<"open success";
}
二、创建表
const QString sql=R"(
CREATE TABLE IF NOT EXISTS produceTable (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
barCode CHAR (50) UNIQUE NOT NULL,
waybillCode CHAR (50) NOT NULL,
bindRes CHAR (50),
checkRes CHAR (50),
dateTime DATETIME NOT NULL
);)";
QSqlQuery query(db);
if(query.exec(sql)){
qDebug()<<"init table success";
}else{
qDebug()<<"init table error"<<query.lastError();
}
三、增
QSqlQuery query(db);
if(query.exec(QString(R"(INSERT INTO produceTable(barCode,waybillCode,dateTime) VALUES('%1','%2',datetime(CURRENT_TIMESTAMP, 'localtime'));)")
.arg("name").arg("SF1124315978")))
{
qDebug()<<"add data success";
}
else
{
qDebug()<<"add data success"<<query.lastError();
}
四、删
QSqlQuery query(db);
if(query.exec(QString(R"(DELETE FROM produceTable WHERE barCode='%1';)")
.arg("name")))
{
qDebug()<<"delete data success";
}
else
{
qDebug()<<"delete data error"<<query.lastError();
}
五、改
QSqlQuery query(db);
if(query.exec(QString(R"(UPDATE produceTable SET bindRes='%2' WHERE barCode='%1';)")
.arg("name").arg("success")))
{
qDebug()<<"update data success";
}
else
{
qDebug()<<"update data error"<<query.lastError();
}
六、查
QSqlQuery query;
if(query.exec(QString(R"(SELECT id,barCode,waybillCode,bindRes,checkRes,dateTime FROM produceTable;)")))
{
qDebug()<<"find data success";
}
else
{
qDebug()<<"find data error"<<query.lastError();
}
while(query.next()){
qDebug()<<query.value(0).toString();
qDebug()<<query.value(1).toString();
qDebug()<<query.value(2).toString();
qDebug()<<query.value(3).toString();
qDebug()<<query.value(4).toString();
qDebug()<<query.value(5).toString();
}
|