100 lines
2.3 KiB
C++
100 lines
2.3 KiB
C++
#include "sql.h"
|
|
|
|
sql::sql()
|
|
{
|
|
//创建数据库
|
|
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //添加驱动
|
|
db.setDatabaseName("SmartGreenhouse.db"); //设置库名
|
|
bool ok = db.open();
|
|
if(!ok){
|
|
qDebug("open failed");
|
|
return ;
|
|
}
|
|
else {
|
|
qDebug()<<"open success";
|
|
}
|
|
|
|
//通过db创建表
|
|
//db.exec("create table usr (name text, passwd text); ");
|
|
|
|
|
|
//通过query创建表
|
|
QSqlQuery query;
|
|
ok = query.exec("create table if not exists user (id text, name text);");
|
|
if(!ok){
|
|
qDebug("failed to create user table");
|
|
}
|
|
else {
|
|
// qDebug()<<"create table success";
|
|
qDebug()<<"Student table created successfully";
|
|
}
|
|
ok = query.exec("create table if not exists Data (temp text, hum text,light text,co2 text);");
|
|
if(!ok){
|
|
qDebug("failed to create Data table");
|
|
}
|
|
else {
|
|
qDebug()<<"Data table created successfully";
|
|
}
|
|
|
|
|
|
//插入数据库
|
|
|
|
/*QString id = ui->lineEdit->text();
|
|
QString name = ui->lineEdit_2->text();
|
|
|
|
|
|
QString sql = QString("insert into stu values ('%1','%2')").arg(id).arg(name);
|
|
|
|
qDebug()<<"sql:"<<sql;
|
|
|
|
QSqlQuery query;
|
|
bool ok;
|
|
ok = query.exec(sql);
|
|
if(!ok){
|
|
qDebug()<<"insert table failed";
|
|
}
|
|
else {
|
|
qDebug()<<"insert table success";
|
|
}*/
|
|
|
|
|
|
//删除一条记录 根据学号来删除
|
|
/*
|
|
QString id = ui->lineEdit->text();
|
|
|
|
QString sql = QString("delete from stu where id='%1'").arg(id);
|
|
|
|
qDebug()<<"sql:"<<sql;
|
|
|
|
QSqlQuery query;
|
|
bool ok;
|
|
ok = query.exec(sql);
|
|
if(!ok){
|
|
qDebug()<<"delete table failed";
|
|
}
|
|
else {
|
|
qDebug()<<"delete table success";
|
|
}*/
|
|
|
|
//查询数据库
|
|
|
|
/* QString sql = QString("select * from stu;");
|
|
|
|
qDebug()<<"sql:"<<sql;
|
|
|
|
QSqlQuery query;
|
|
bool ok;
|
|
ok = query.exec(sql);
|
|
if(!ok){
|
|
qDebug()<<"select table failed";
|
|
}
|
|
else {
|
|
qDebug()<<"select table success";
|
|
}
|
|
|
|
while(query.next()){
|
|
|
|
qDebug()<< query.value("name").toString();
|
|
}*/
|
|
}
|