所以我在代码上遗漏了一些内容,但我无法弄清楚这是什么。我试图将一些值从文本字段中删除到数据库中,但我得到了文章名称的错误。
有人可以帮忙吗? 我发布了isert代码和按钮代码。 提前谢谢。
Database.cpp
bool Database::insertStudent(Student &s)
{
bool success = false;
QSqlQuery query(db);
query.prepare("INSERT INTO student (name,lastname,semester,studentid) VALUES (:name,:lastname,:semester,:studentid)");
query.bindValue(":name", s.getname());
query.bindValue(":lastname",s.getlastname());
query.bindValue(":semester", s.getsemester());
query.bindValue(":studentid",s.getstudentid());
query.exec();
if(query.exec()) success = true;
else
{
qDebug() << "Database error: "
<< query.lastError();
}
return success;
}
MainWindow.cpp
void MainWindow::addSlot()
{
if(nameEdit->text().isEmpty() || lastnameEdit->text().isEmpty() || semesterEdit->text().isEmpty() ||
idEdit->text().isEmpty())
{
QMessageBox::critical(this,"Error","Empty fields");
return;
}
Student S(nameEdit->text(),lastnameEdit->text(),semesterEdit->text().toInt(),idEdit->text().toInt());
mydb->insertStudent(S);
reloadTable();
}
表名是学生,它有4个我使用此代码创建的字段。
Database::Database()
{
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("students.db");
db.open();
QSqlQuery q(db);
q.exec(QString("create table if not exists student(")+
QString("id integer primary key autoincrement,")+
QString("name varchar(1024),lastname varchar(1024),semester integer,")+
QString("studentid integer)"));
}
student.cpp
#include "student.h"
Student::Student()
{
name="";
lastname="";
studentid=0;
semester=0;
}
Student::Student(QString n,QString l,int s,int p)
{
name=n;
lastname=l;
semester=s;
studentid=p;
}
QString Student::getname()
{
return name;
}
QString Student::getlastname()
{
return lastname;
}
int Student::getstudentid()
{
return studentid;
}
int Student::getsemester()
{
return semester;
}
QString Student::toString()
{
return name+","+lastname+","+QString::number(semester)+","+QString::number(studentid);
}