qt实现通过界面输入数据库表名和列数据信息,创建一张数据库表的程序
时间: 2024-05-04 18:18:25 浏览: 139
下面是一个简单的 Qt 程序,可以通过界面输入数据库表名和列数据信息,创建一张数据库表。
```cpp
#include <QtWidgets>
#include <QtSql>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建数据库连接
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("mydatabase.db");
if (!db.open()) {
QMessageBox::critical(nullptr, QObject::tr("无法打开数据库"),
QObject::tr("无法建立到指定数据库的连接。"),
QMessageBox::Cancel);
return -1;
}
// 创建界面
QWidget window;
window.setWindowTitle("创建数据库表");
QLabel *labelTableName = new QLabel("表名:");
QLineEdit *editTableName = new QLineEdit;
QHBoxLayout *layoutTableName = new QHBoxLayout;
layoutTableName->addWidget(labelTableName);
layoutTableName->addWidget(editTableName);
QLabel *labelColumnNames = new QLabel("列名(用逗号分隔):");
QLineEdit *editColumnNames = new QLineEdit;
QHBoxLayout *layoutColumnNames = new QHBoxLayout;
layoutColumnNames->addWidget(labelColumnNames);
layoutColumnNames->addWidget(editColumnNames);
QLabel *labelColumnTypes = new QLabel("列类型(用逗号分隔):");
QLineEdit *editColumnTypes = new QLineEdit;
QHBoxLayout *layoutColumnTypes = new QHBoxLayout;
layoutColumnTypes->addWidget(labelColumnTypes);
layoutColumnTypes->addWidget(editColumnTypes);
QVBoxLayout *layout = new QVBoxLayout;
layout->addLayout(layoutTableName);
layout->addLayout(layoutColumnNames);
layout->addLayout(layoutColumnTypes);
QPushButton *buttonCreateTable = new QPushButton("创建表");
layout->addWidget(buttonCreateTable);
window.setLayout(layout);
window.show();
// 创建表
QObject::connect(buttonCreateTable, &QPushButton::clicked, [&]() {
QString tableName = editTableName->text();
QString columnNames = editColumnNames->text();
QString columnTypes = editColumnTypes->text();
QStringList columnNamesList = columnNames.split(",");
QStringList columnTypesList = columnTypes.split(",");
if (columnNamesList.size() != columnTypesList.size()) {
QMessageBox::critical(nullptr, QObject::tr("错误"),
QObject::tr("列名和列类型的数量不一致。"),
QMessageBox::Cancel);
return;
}
QSqlQuery query(db);
QString sql = QString("CREATE TABLE %1 (").arg(tableName);
for (int i = 0; i < columnNamesList.size(); ++i) {
sql += QString("%1 %2,").arg(columnNamesList[i]).arg(columnTypesList[i]);
}
sql.chop(1); // 去掉最后一个逗号
sql += ")";
if (!query.exec(sql)) {
QMessageBox::critical(nullptr, QObject::tr("错误"),
query.lastError().text(),
QMessageBox::Cancel);
return;
}
QMessageBox::information(nullptr, QObject::tr("成功"),
QObject::tr("创建表成功。"),
QMessageBox::Ok);
});
return app.exec();
}
```
该程序创建一个包含三个文本框和一个按钮的窗口,用户可以在文本框中输入表名、列名和列类型,然后单击按钮创建表。注意,该程序仅限于 SQLite 数据库,如果您使用的是其他类型的数据库,请修改 `QSqlDatabase::addDatabase` 和 `QSqlQuery` 的参数。
阅读全文