我用qt做的学生信息管理系统界面中的line edit表格怎么连接数据库,并实现增删改查功能,具体代码是什么
时间: 2024-03-25 19:36:40 浏览: 61
连接数据库可以使用Qt自带的QtSql模块来实现,具体操作步骤如下:
1.在.pro文件中添加QT += sql
2.创建数据库连接
```cpp
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost"); //主机名
db.setDatabaseName("testdb"); //数据库名
db.setUserName("root"); //用户名
db.setPassword("password"); //密码
if (!db.open()) {
qDebug() << "Unable to connect to database";
}
```
3.执行SQL语句
```cpp
QSqlQuery query;
query.exec("SELECT * FROM student");
while (query.next()) {
QString name = query.value(0).toString();
int age = query.value(1).toInt();
QString gender = query.value(2).toString();
qDebug() << name << age << gender;
}
```
4.增删改查操作
```cpp
//添加一条记录
QSqlQuery query;
query.prepare("INSERT INTO student (name, age, gender) VALUES (:name, :age, :gender)");
query.bindValue(":name", "张三");
query.bindValue(":age", 20);
query.bindValue(":gender", "男");
query.exec();
//删除一条记录
query.prepare("DELETE FROM student WHERE name = :name");
query.bindValue(":name", "张三");
query.exec();
//修改一条记录
query.prepare("UPDATE student SET age = :age WHERE name = :name");
query.bindValue(":age", 21);
query.bindValue(":name", "张三");
query.exec();
//查询一条记录
query.prepare("SELECT * FROM student WHERE name = :name");
query.bindValue(":name", "张三");
query.exec();
if (query.next()) {
QString name = query.value(0).toString();
int age = query.value(1).toInt();
QString gender = query.value(2).toString();
qDebug() << name << age << gender;
}
```
对于LineEdit表格的操作,可以通过继承QSqlTableModel来实现,详细代码如下:
```cpp
class MyTableModel : public QSqlTableModel {
public:
MyTableModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase())
: QSqlTableModel(parent, db) {}
Qt::ItemFlags flags(const QModelIndex &index) const override {
return QSqlTableModel::flags(index) | Qt::ItemIsEditable;
}
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override {
if (role == Qt::EditRole) {
bool ok = QSqlTableModel::setData(index, value, role);
submitAll();
return ok;
}
return false;
}
};
//在构造函数中初始化
MyTableModel *model = new MyTableModel(this, db);
model->setTable("student");
model->select();
//将LineEdit绑定到表格中
QDataWidgetMapper *mapper = new QDataWidgetMapper(this);
mapper->setModel(model);
mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
mapper->addMapping(ui->lineEdit_name, 0);
mapper->addMapping(ui->lineEdit_age, 1);
mapper->addMapping(ui->lineEdit_gender, 2);
mapper->toFirst();
```
其中,QDataWidgetMapper用于将LineEdit与表格中的数据进行映射,实现增删改查操作。
阅读全文