调用 QSqlTableModel setTable 方法时出现"Unable to find table"错误
"Unable to find table" error when calling QSqlTableModel setTable method
>我需要通过从QSqlTableModel对象检索数据来填充QTableView。我使用以下命令连接到 sql 服务器数据库:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectionTemplate = "DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Uid=username;Pwd=password;Trusted_Connection=Yes;";
QString connectionString = connectionTemplate.arg("localhost").arg("mydb");
db.setDatabaseName(connectionString);
我通过 QSqlDatabase 类中的 isValid(( 和 open(( 方法来验证数据库连接。我还能够正确地从数据库表中查询。ٍ到目前为止一切都很好。但是当我使用以下命令时出现问题:
QSqlTableModel* model = new QSqlTableModel(parent,db);
model->setTable("mytable");
qDebug() << model->lastError().text(); // the error message is printed on consul.
方法setTable 不起作用并导致错误:找不到表 \"mytable\"。
我找到了解决方案。我应该在setDatabaseName之后和创建QSqlTableModel之前立即打开数据库:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectionTemplate = "DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Uid=username;Pwd=password;Trusted_Connection=Yes;";
QString connectionString = connectionTemplate.arg("localhost").arg("mydb");
db.setDatabaseName(connectionString);
db.open(); // :)
QSqlTableModel* model = new QSqlTableModel(parent,db);
model->setTable("mytable");
根据 http://doc.qt.io/qt-5/qsqltablemodel.html#QSqlTableModelQSqlTablemodel 的构造函数:
创建一个空的 QSqlTableModel,并将父项设置为父项和 数据库与数据库的连接。如果 db 无效,则默认数据库 将使用连接。
如果您的数据库对象无效,您将连接到表不可用的默认数据库。
仔细检查用于初始化和设置 QSqlDatabase db 的参数。
相关文章:
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- Win32 API - HWND "{unused = ???} Unable to read memory"错误
- 从生成文件编译错误:"Unable to open output file" ..."No such file or directory"
- 如何在qt中修复"No query Unable to fetch row"
- 类型字符串::长度()。我得到了"Unable to resolve identifier length"
- Qt应用程序中的"No query Unable to fetch row"
- 如何处理"Cmake Error: Unable to find the requested Boost libraries"?
- MSVC:带函数的"error C2244: unable to match function definition to an existing declaration"是指专用模板类的类型别名
- 使用 Korge 编译本机时"Unable to find library"抛出错误
- QNetwork回复 "unable to write"
- AWS 批处理"unable to connect to endpoint"
- 仅在一台计算机上出现"0xc000007b Application Unable to Start Correctly"错误
- "Unable to open file libc++abi.dylib" .程序生成,但在运行时崩溃。使用 xcode 10.1 (10B61)
- 调用 QSqlTableModel setTable 方法时出现"Unable to find table"错误
- 为什么 void 排序(int *[], int) 会导致"Unable to read memory"?
- 如何设置Visual Studio来调试DLL ("Unable to start program error")
- PCC-S-02015, "unable to open include file"
- 在 exiv2 中"unable to parse" IPTC 日期到 XMP 日期时间
- "Unable to resolve template based identifier X" - 从模板类调用模板参数类的方法 (C++)
- AWS S3 aws-sdk-cpp GetObject "Unable to connect to endpoint"