c++ - 如何返回可读的数据

标签 c++ qt

我读了这篇文章http://www.slideshare.net/redigon/refactoring-1658371 在第 53 页上,它指出“您有一个返回值但也更改对象状态的方法。创建两个方法,一个用于查询,一个用于修改。

但是如果在查询中我需要超过 1 个字段的值怎么办。

例如:

QSqlQuery query(QSqlDatabase::database("MAIN"));
QString command = "SELECT FIELD1, FIELD2, FIELD3, FIELD4, FIELD5 FROM TABLE";
query.exec( command );

这是我知道的方法,但我真的觉得这不是那么可读

QString values;
columnDelimiter = "[!@#]";
rowDelimiter = "[$%^]";
while( query.next )
{
    values += query.value(0).toString() + columnDelimiter;
    values += query.value(1).toString() + columnDelimiter;
    values += query.value(2).toString() + columnDelimiter;
    values += query.value(3).toString() + columnDelimiter;
    values += rowDelimiter;
}

我会像这样检索它。

QStringList rowValues, columnValues;

rowValues = values.split(rowDelimiter);

int rowCtr =0;

while( rowCtr < rowValues.count() )
{
    columnValues.clear();
    // Here i got the fields I need
    columnValues = rowValues.at( rowCtr ).split( columnDelimiter );
    // I will put the modification on variables here

    rowCtr++;

}

编辑:有没有更易读的方法?

最佳答案

“是否有更易读的方法来做到这一点?” 是一个主观问题。我不确定你的问题是否会持续很长时间,因为 SO 更喜欢事实问题和解决方案。

我个人认为将使您的代码更具可读性的是:

  • 为您的数据集使用定制的数据结构。字符串不是表格数据的正确数据结构。自定义结构列表更好。

例子:

// data structure for a single row
struct MyRow {
    QString a, b, c;
}

...

QList<MyRow> myDataSet;
while( query.next )
{
    MyRow currentRow;
    // fill with data
    currentRow.a = query.value(0).toString();
    currentRow.b = query.value(1).toString();
    ...

    myDataSet.append(currentRow);
}
  • 我怀疑您的所有数据都是文本。有些可能是数字。切勿将数字存储为字符串。那是低效的。

  • 你先把所有的数据读入一个数据结构,然后读入数据结构进行处理。你为什么不把两者结合起来? IE。在读取数据的同时处理,在相同的 while(...)

  • 在您的评论中,您对 enumstruct 之间的区别感到困惑。我建议,停止做复杂的数据库和 QT 的东西。拿一本基本的 C++ 书,首先尝试理解 C++。

关于c++ - 如何返回可读的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644988/

相关文章:

c++ - VS2017 version 15.8.3 成功编译内联方法不返回所需值

c++ - libm.lib、libmmt.lib 和 libmmds.lib 之间有什么区别?

c++ - Phong-Alpha Material 透明度

c++ - 如何使用颜色将 QPlainTextEdit 内容渲染到 QPixmap?

c++ - 使用 OpenCV 的低质量空中拼接

C++ - 将 OpenGL 与代码块一起使用?

c++ - 模板非类型参数和分配数组内存

c++ - Qt中如何跨不同的对话框存储变量

android - 如何使用 Qt Creator 运行 ADB 命令?

c++ - 继承和 Qt 信号