【问题标题】:Get primaryKey programmatically with Qt使用 Qt 以编程方式获取 primaryKey
【发布时间】:2014-07-23 05:07:04
【问题描述】:

我尝试以编程方式获取 primaryKey 并将其转换为 col 名称。此功能无法正常工作。

QString getPrimaryFiled( const QString &tableName )
{
    QSqlDatabase m_SqlDataBase = QSqlDatabase::database(StaticConnection::getDatabaseConnectionName());
    return m_SqlDataBase.primaryIndex( tableName ).name();
}

但我找不到让它工作的方法,它给了我空白字符串

【问题讨论】:

  • 您是否验证了相关表确实有主键?如果是这样,它是什么?
  • 不使用Qt你的表还好吗?
  • @AndrewMedico 是的,我的主键是IdMedicalRcipeTitleLogo
  • @FinalContest 是的,Qt 也一样。
  • QSqlDatabase::database()static 方法,您使用的 QSqlDatabase 无效。

标签: c++ qt qtsql qsqldatabase


【解决方案1】:

您误用了以下方法:

QSqlDatabase QSqlDatabase::database(const QString & connectionName = QLatin1String( defaultConnection ), bool open = true) [static]

返回名为 connectionName 的数据库连接。数据库连接必须先前已使用 addDatabase() 添加。如果 open 为 true(默认值)并且数据库连接尚未打开,则现在将其打开。如果未指定 connectionName,则使用默认连接。如果数据库列表中不存在connectionName,则返回无效连接。

你应该这样写的:

QSqlDatabase m_SqlDataBase = QSqlDatabase::database( StaticConnection::getDatabaseConnectionName() );

前提是您正确遵循了有关 addDatabase() 的文档。

【讨论】:

  • 这是我用来获取连接名称的函数。
  • @AmrEisa:请仔细阅读答案。 不是说罪魁祸首是你的数据库名称查询函数。
  • 我抓住你了。它已打开,我确信我编辑了我的第一篇文章以使代码更清晰。
  • @AmrEisa:当然它不起作用,因为您没有遵循上面的文档。
  • 我这样做了,通过这个调用 m_SqlDataBase.primaryIndex(tableName).fieldName(0);但我不需要这是对 fieldName(0) 的静态调用
猜你喜欢
  • 2015-11-17
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
相关资源
最近更新 更多