增加txt2db、db2txt功能

This commit is contained in:
一二三 2023-06-21 00:17:06 +08:00
parent 0a941954e0
commit 0d66beb3ca
3 changed files with 226 additions and 0 deletions

View File

@ -1,4 +1,5 @@
QT += core gui QT += core gui
QT += sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

View File

@ -2,10 +2,16 @@
#include "ui_mainwindow.h" #include "ui_mainwindow.h"
#include <QFile> #include <QFile>
#include <QTextStream> #include <QTextStream>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QTableWidget> #include <QTableWidget>
#include <QFileDialog> #include <QFileDialog>
#include <QProgressDialog> #include <QProgressDialog>
#include <QMessageBox> #include <QMessageBox>
#include <QInputDialog>
#include <QSqlRecord>
#include <QtDebug>
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
@ -26,6 +32,17 @@ MainWindow::MainWindow(QWidget *parent)
ui->actionOpen->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N)); ui->actionOpen->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N));
ui->actionSave->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S)); ui->actionSave->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
// 添加 "Convert" 菜单
QMenu* convertMenu = menuBar()->addMenu(tr("Convert"));
// 添加 "Text to SQLite" 子菜单项,并关联槽函数
QAction* textToSqliteAction = convertMenu->addAction(tr("Text to SQLite"));
connect(textToSqliteAction, &QAction::triggered, this, &MainWindow::convertTextToSqlite);
// 添加 "SQLite to Text" 子菜单项,并关联槽函数
QAction* sqliteToTextAction = convertMenu->addAction(tr("SQLite to Text"));
connect(sqliteToTextAction, &QAction::triggered, this, &MainWindow::convertSqliteToText);
} }
MainWindow::~MainWindow() MainWindow::~MainWindow()
@ -192,3 +209,209 @@ void MainWindow::dropEvent(QDropEvent *event)
} }
} }
} }
void MainWindow::convertTextToSqlite()
{
// 选择要读取的文本文件
QString textFilePath = QFileDialog::getOpenFileName(this, tr("Select Text File"), "", tr("Text Files (*.txt)"));
if (textFilePath.isEmpty())
return;
// 选择要保存的SQLite文件
QString sqliteFilePath = QFileDialog::getSaveFileName(this, tr("Save SQLite File"), "", tr("SQLite Files (*.sqlite)"));
if (sqliteFilePath.isEmpty())
return;
// 打开文本文件并读取内容
QFile textFile(textFilePath);
if (!textFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::critical(this, tr("Error"), tr("Failed to open text file."));
return;
}
QTextStream textStream(&textFile);
// 跳过第一行
if (!textStream.atEnd())
{
textStream.readLine();
}
// 读取第二行作为列名
QStringList columnNames;
if (!textStream.atEnd())
{
QString secondLine = textStream.readLine();
// 处理列名,将空格替换为下划线,将点号替换为下划线
QString processedLine = secondLine.replace(" ", "_").replace(".", "_");
// 将处理后的列名拆分为多个列名(以制表符为分隔符)
columnNames = processedLine.split('\t', Qt::SkipEmptyParts);
}
//QTextStream textStream2(&textFile);
QList<QStringList> data;
textStream.seek(0);
// 读取数据行
while (!textStream.atEnd())
{
QString line = textStream.readLine();
QStringList values = line.split("\t");
data.append(values);
}
textFile.close();
// 打开SQLite数据库
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName(sqliteFilePath);
if (!database.open())
{
QMessageBox::critical(this, tr("Error"), tr("Failed to open SQLite database."));
return;
}
// 创建表并插入数据
QSqlQuery query(database);
QString createTableQuery = "CREATE TABLE IF NOT EXISTS ref_list (";
for (const QString& columnName : columnNames)
{
createTableQuery += "\"" + columnName + "\" TEXT, ";
}
createTableQuery.chop(2); // 移除最后的逗号和空格
createTableQuery += ");";
if (!query.exec(createTableQuery))
{
QMessageBox::critical(this, tr("Error"), tr("Failed to create table: %1").arg(query.lastError().text()));
database.close();
return;
}
database.transaction();
QString insertQuery = "INSERT INTO ref_list VALUES (";
for (int i = 0; i < columnNames.size(); ++i)
{
insertQuery += "?, ";
}
insertQuery.chop(2); // 移除最后的逗号和空格
insertQuery += ");";
for (const QStringList& row : data)
{
if (row.size() != columnNames.size())
{
qDebug() << "Mismatched value count in row: " << row;
continue; // Skip this row and proceed to the next row
}
query.prepare(insertQuery);
for (int i = 0; i < row.size(); ++i)
{
query.addBindValue(row[i]);
}
if (!query.exec())
{
QMessageBox::critical(this, tr("Error"), tr("Failed to insert row: %1").arg(query.lastError().text()));
database.rollback();
database.close();
return;
}
}
database.commit();
database.close();
QMessageBox::information(this, tr("Conversion Complete"), tr("Text to SQLite conversion completed successfully."));
}
void MainWindow::convertSqliteToText()
{
// Select the SQLite file
QString sqliteFilePath = QFileDialog::getOpenFileName(this, tr("Select SQLite File"), "", tr("SQLite Files (*.sqlite)"));
if (sqliteFilePath.isEmpty())
return;
// Select the text file to save
QString textFilePath = QFileDialog::getSaveFileName(this, tr("Save Text File"), "", tr("Text Files (*.txt)"));
if (textFilePath.isEmpty())
return;
// Open the SQLite database
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName(sqliteFilePath);
if (!database.open())
{
QMessageBox::critical(this, tr("Error"), tr("Failed to open SQLite database."));
return;
}
// Retrieve the table name from the user
QStringList tables = database.tables();
if (tables.isEmpty())
{
QMessageBox::information(this, tr("No Tables"), tr("The SQLite database does not contain any tables."));
database.close();
return;
}
// Select the table to export
bool ok;
QString selectedTable = QInputDialog::getItem(this, tr("Select Table"), tr("Select a table to export:"), tables, 0, false, &ok);
if (!ok || selectedTable.isEmpty())
{
database.close();
return;
}
// Execute a query to retrieve all data from the selected table
QSqlQuery query;
query.prepare(QString("SELECT * FROM %1").arg(selectedTable));
if (!query.exec())
{
QMessageBox::critical(this, tr("Error"), tr("Failed to execute query: %1").arg(query.lastError().text()));
database.close();
return;
}
// Open the text file to write data
QFile textFile(textFilePath);
if (!textFile.open(QIODevice::WriteOnly))
{
QMessageBox::critical(this, tr("Error"), tr("Failed to open text file."));
database.close();
return;
}
// Write the BOM (Byte Order Mark) for UTF-16LE encoding
QByteArray bom;
bom.append((char)0xFF);
bom.append((char)0xFE);
textFile.write(bom);
QTextStream textStream(&textFile);
textStream.setCodec("UTF-16LE");
// Write the data to the text file
while (query.next())
{
QSqlRecord record = query.record();
for (int i = 0; i < record.count(); ++i)
{
QVariant value = record.value(i);
textStream << value.toString();
if (i < record.count() - 1)
textStream << "\t";
}
textStream << "\r\n";
}
textFile.close();
database.close();
QMessageBox::information(this, tr("Conversion Complete"), tr("SQLite to Text conversion completed successfully."));
}

View File

@ -23,6 +23,8 @@ public:
void loadTextFile(const QString& fileName); void loadTextFile(const QString& fileName);
void dragEnterEvent(QDragEnterEvent *event); void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event); void dropEvent(QDropEvent *event);
void convertTextToSqlite();
void convertSqliteToText();
private slots: private slots:
void onOpenButtonClicked(); void onOpenButtonClicked();