Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt/SQL - Get column type and name from table without record

Tags:

c++

types

sql

qt

Using Qt, I have to connect to a database and list column's types and names from a table. I have two constraints:

1 The database type must not be a problem (This has to work on PostgreSQL, SQL Server, MySQL, ...)

2 When I looked on the internet, I found solutions that work but only if there are one or more reocrd into the table. And I have to get column's type and name with or without record into this database.

I searched a lot on the internet but I didn't find any solutions.

I am looking for an answer in Qt/C++ or using a query that can do that.

Thanks for help !

like image 331
Tristan Djahel Avatar asked Sep 16 '13 13:09

Tristan Djahel


2 Answers

QSqlDriver::record() takes a table name and returns a QSqlRecord, from which you can fetch the fields using QSqlRecord::field().

So, given a QSqlDatabase db,

  1. fetch the driver with db.driver(),
  2. fetch the list of tables with db.tables(),
  3. fetch the a QSqlRecord for each table from driver->record(tableName), and
  4. fetch the number of fields with record.count() and the name and type with record.field(x)
like image 133
Hamish Moffatt Avatar answered Sep 23 '22 00:09

Hamish Moffatt


According to the previous answers, I make the implementation as below.It can work well, hope it can help you.

  {
      QSqlDatabase db = QSqlDatabase::addDatabase("QSLITE", "demo_conn"); //create a db connection
      QString strDBPath = "db_path";
      db.setDatabaseName(strDBPath); //set the db file
      QSqlRecord record = db.record("table_name"); //get the record of the certain table
      int n = record.count();
      for(int i = 0; i < n; i++)
      {
        QString strField = record.fieldName(i);
      }
    }
    QSqlDatabase::removeDatabase("demo_conn"); //remove the db connection
like image 41
StephennQin Avatar answered Sep 23 '22 00:09

StephennQin