When i will view the data from my mysql database " mydb " , from the table "testtable", it cant open the database.
this->model = new QSqlQueryModel();
meineView->setModel(model);
must i write it so :
model->setQuery("SELECT id, Nachname, Vorname, Ort FROM mydb");
Or so ? :
model->setQuery("SELECT `testtable`.`id`,`testtable`.`Nachname`,`testtable`.`Vorname`,`testtable`.`Ort`FROM `mydb`.`testtable`;");
what do i wrong ? when i delete this , my program works ( without views the data )
and when i can open it, how i put the data in my table ? ?
You need to call overriden method with your Database name. Because the database you are trying to open is not default database.
Try this :
model->setQuery("SELECT `testtable`.`id`,`testtable`.`Nachname`,`testtable`.`Vorname`,`testtable`.`Ort
`FROM `mydb`.`testtable`;","mydb");
First of all you need to connect to database using QSqlDatabase class. Then you can connect QSqlQueryModel to sql connection using proper sql query.
your first query is wrong because mydb is the database and this query needs table name:
SELECT id, Nachname, Vorname, Ort FROM testtable.
Second query is the option to choose when the query references multiple tables.
SELECT testable.id, testable.name, othertable.data FROM testable, othertable, WHERE testable.someRow = othertable.someRow
Related
I have a table that contains duplicated records.
I used following code to put the data into a QTableView:
QSqlTableModel *dataModel = new QSqlTableModel();
dataModel->setTable("table_name");
dataModel->select();
now I wanna to query duplicated records. I use group by and having for do that in sql but I haven`t any idea to how do this in qt.
Finally I found the solution, I used "setFilter" method as bellow:
dataModel = new QSqlTableModel();
dataModel->setTable("CUSTOMER");
QString filter_txt = "id in (select id FROM CUSTOMER GROUP BY id HAVING count(*) >1)" ;
dataModel->setFilter(filter);
dataModel->select();
In my app in QT5 I have this code
QString sql = "Select * from table";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./au.sqlite");
db.open();
QSqlQuery query(sql);
query.exec();
But when I get the results only get one result, the select query only give me one result and I don't know how fix this. If I add query.next() in a while loop I only get one iteration.
There is a bool function that returns true if the query succeeded. Looking back to the docs:
Successfully executed SQL statements set the query's state to active so that isActive() returns true. Otherwise the query's state is set to inactive.
This is the way you can check the result. If it's false, then You should try to rewrite your sql query text so that functional sql words (such as SELECT, FROM and etc.) are in the upper case (the way it's shown in the docs) and try to execute the query once again.
Here's an example from the docs again:
QSqlQuery query("SELECT country FROM artist");
while (query.next()) {
QString country = query.value(0).toString();
doSomething(country);
}
You might check sqlbrowser example that is included with Qt5 distribution. Run your query there on your db.
I have written a QT GUI application that connects to an Oracle Database and performs query and shows the output in a QTableView.
QString host_name=ui->lineHostName->text();
QString db_name=ui->lineDatabaseName->text();
QString user_name=ui->lineUserName->text();
QString pass_word=ui->linePassword->text();
QString port_no=ui->linePortNumber->text();
QSqlDatabase db = QSqlDatabase::addDatabase("QOCI");
db.setHostName(host_name);
db.setDatabaseName(db_name);
db.setUserName(user_name);
db.setPassword(pass_word);
db.setPort(port_no.toInt());
QString MyQuery = ui->lineQuery->text();
db.open();
QSqlQuery query(MyQuery,db);
if(query.exec())
{
this->model=new QSqlQueryModel();
model->setQuery(MyQuery);
ui->tableViewOra->setModel(model);
}
After running the program, I tried to use this (as a substitute of the DESC )---
SELECT
column_name "Name",
nullable "Null?",
concat(concat(concat(data_type,'('),data_length),')') "Type"
FROM user_tab_columns
WHERE table_name='my_table_number_one';
And the column names, null parameter and data type was shown on the QTableView
Now my question is, can I use this information in the QTableView to create another table with same Column names and data type ??? (Basically creating a copy of my queried table table).
EDIT
After suggestions i tried modifying with---
QString query_to_replicate;
query_to_replicate=QString("CREATE OR REPLACE TABLE %1 AS %2").arg("AJ_REPLACEMENT_TESTING").arg(ui->lineEdit->text());
QSqlQuery query_second(query_to_replicate,db);
if(query_second.exec())
{
ui->r_pop_Button->setStyleSheet("QPushButton {background-color: rgb(0, 255, 0);}");
this->model_relocate=new QSqlQueryModel();
model_relocate->setQuery(query_second);
ui->tableView2->setModel(model_relocate);
while (model_relocate->canFetchMore())
model_relocate->fetchMore();
qDebug()<<QDateTime::currentDateTime()<<"Query SUCCESS ";
db.close();
}
now it worked twice, without throwing errors and created replicated copies in the oracle database (I used different names for replicated table before building).
But after running successfully twice, it seized replicating. Situation is completely clueless. I am not getting any errors during build / compile time.
You can do this by using CREATE TABLE AS SELECT:
QString sql = "CREATE TABLE %1 AS %2"
.arg(yourNewTableName)
.arg(ui->lineQuery->text());
// and execute this sql code on your QSqlDatabase as you do it above
It will create new table, with name from "yourNewTableName" variable and copy data from select query to new table.
Code update:
QString query_to_replicate;
query_to_replicate=QString("CREATE OR REPLACE TABLE %1 AS %2").arg("AJ_REPLACEMENT_TESTING").arg(ui->lineEdit->text());
QSqlQuery query_second(query_to_replicate,db); // query will be executed there! weird, but...
if (query_second.lastError().isValid())
{
qDebug() << query_second.lastError().text(); // error happens
}
else
{
qDebug() << "Table created successfully";
}
Also, you must #include <QSqlError> in the top of file, to use QtSql errors.
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 !
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,
fetch the driver with db.driver(),
fetch the list of tables with db.tables(),
fetch the a QSqlRecord for each table from driver->record(tableName), and
fetch the number of fields with record.count() and the name and type with record.field(x)
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
Getting column names and types is a database-specific operation. But you can have a single C++ function that will use the correct sql query according to the QSqlDriver you currently use:
QStringlist getColumnNames()
{
QString sql;
if (db.driverName.contains("QOCI", Qt::CaseInsensitive))
{
sql = ...
}
else if (db.driverName.contains("QPSQL", Qt::CaseInsensitive))
{
sql = ...
}
else
{
qCritical() << "unsupported db";
return QStringlist();
}
QSqlQuery res = db.exec(sql);
...
// getting names from db-specific sql query results
}
I don't know of any existing mechanism in Qt which allows that (though it might exist - maybe by using QSqlTableModel). If noone else knows of such a thing, I would just do the following:
Create data classes to store the information you require, e.g. a class TableInfo which stores a list of ColumnInfo objects which have a name and a type.
Create an interface e.g. ITableInfoReader which has a pure virtual TableInfo* retrieveTableInfo( const QString& tableName ) method.
Create one subclass of ITableInfoReader for every database you want to support. This allows doing queries which are only supported on one or a subset of all databases.
Create a TableInfoReaderFactory class which allows creation of the appropriate ITableInfoReader subclass dependent on the used database
This allows you to have your main code independent from the database, by using only the ITableInfoReader interface.
Example:
Input:
database: The QSqlDatabase which is used for executing queries
tableName: The name of the table to retrieve information about
ITableInfoReader* tableInfoReader =
_tableInfoReaderFactory.createTableReader( database );
QList< ColumnInfo* > columnInfos = tableInfoReader->retrieveTableInfo( tableName );
foreach( ColumnInfo* columnInfo, columnInfos )
{
qDebug() << columnInfo.name() << columnInfo.type();
}
I found the solution. You just have to call the record function from QSqlDatabase. You have an empty record but you can still read column types and names.
Im working on a project where im trying to build a QTreeWidget that has multiple QTreeWidgetItems
and once i click on a particular item it connects to a database and shows a query result in a tableview model, until now every thing works fine.
the problem is that i want each item to output different resut depending on some criteria on the same table where this criteria is only changing the value of an attribute, and this value is the same of the item name. for example item named 122 and the table has atribute called no. when we click on item 122 the result of this query must be shown (select * from table where no=122)
any help :)
I am assuming you have a QTableView backed by a QSqlQueryModel or QSqlTableModel.
You can connect to the signal QTreeWidget::itemSelectionChanged() and then in the slot you get the current item with selectedItems()[0]. Then you create your query:
QSqlQuery query;
query.prepare("select * from table where no=:no");
query.bindValue(":no", number);
query.exec();
Finally you can use setQuery (const QSqlQuery & query) on the model. This should update your view.
I hope I understood correctly what you want to achieve.