所以我在代码上遗漏了一些东西,但我不知道这是什么。我正在尝试将文本字段中的一些值插入数据库,但我收到文章名称的错误。
有人可以帮忙吗?我正在发布 isert 代码和按钮代码。提前致谢。
数据库.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;
}
主窗口.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)"));
}
学生.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);
}