Inserting binary data via QSQL - c++

How to insert binary data to table "test" from "database" with 2 columns text "name" and bin "pic"
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setUserName("user");
db.setPassword("pwd");
db.setPort(1234);
db.setDatabaseName("database");

You can have a look at http://www.java2s.com/Code/Cpp/Qt/UsingsqldatabasefromQt.htm snippets
First you need to open the DB db.open();
One way would be
QSqlQuery query;
query.prepare("INSERT INTO test (name, pic) "
"VALUES (:name, :pic)");
query.bindValue(":name", "Bart");
query.bindValue(":pic", "Bart.jpg");
query.exec();

Related

Creating a new table in database with description from existing table as an input

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.

QSqlQueryModel dont can open database

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

Why do INSERT and DELETE screw up QTableView (Qt, C++, sqlite)?

After setting an INSERT or DELETE query on QSqlQueryModel, my QTableView becomes screwed up. For example I hid the ID column by calling view->hideColumn(ID); but after an INSERT or DELETE the ID column becomes visible.
How can I automatically reset my view to the previous settings in these cases?
I guess the problem is in QSqlQueryModel::setQuery you're eventually calling every time content gets reloaded and rows inserts\deletes. Looking at the setQuery implementation I would suggest: depending on the query your model can be reset including columns settings change which should trigger view columns update.
As Qt documentation suggests:
The QSqlQueryModel class provides a
read-only data model for SQL result
sets.
so I would use direct QSqlQuery calls for the data updates and then would reload the model with the same query. Or consider switching to QSQLTableModel, which is quite handy for single table content manipulation and supports inserts updates and deletes. See if an example below would work for you:
set up database, view and model:
QSqlTableModel *_model;
QTableView *_view;
...
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open() ;
QSqlQuery query;
query.prepare("CREATE TABLE IF NOT EXISTS person (id INTEGER UNIQUE PRIMARY KEY, name VARCHAR(30))");
query.exec();
query.prepare("INSERT INTO person (name) VALUES ('test1')");
query.exec();
query.prepare("INSERT INTO person (name) VALUES ('test2')");
query.exec();
_model = new QSqlTableModel(this, db);
_model->setTable("person");
_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
_model->select();
_model->setHeaderData(1, Qt::Horizontal, tr("name"));
_model->setSort(1, Qt::AscendingOrder);
_view = new QTableView(this);
_view->setModel(_model);
_view->hideColumn(0);
add new row:
QSqlRecord record;
_model->insertRecord(-1, record);
delete selected row(s):
QModelIndexList selected = _view->selectionModel()->selectedIndexes();
for (int i = 0; i < selected.size(); ++i)
_model->removeRows(selected.at(i).row(), 1);
submit changes:
_model->submitAll();
hope this helps, regards

Database creation error in Qt

I am using this code to create a database. But I am getting "false" in debug. I tried a lot but its not working. What is the error in this?
QSqlQuery query;
qDebug() << query.exec("CREATE TABLE glucose (id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER, date TEXT, time TEXT, duration TEXT, note TEXT");
qDebug() << query.prepare("INSERT INTO glucose(id, value, date, time, duration, note)""VALUES(?, ?, ?, ?, ?, ?)");
query.bindValue(1,edit_glucose->text().toInt());
query.bindValue(2,datetime->date());
query.bindValue(3,datetime->time());
query.bindValue(4,"a");
query.bindValue(5,edit_note->toPlainText());
qDebug() << query.exec();
you forget to close your CREATE TABLE query with ")"
QSqlQuery has the method lastError(), returns error information :)
You are passing in the INSERT query the id field. You must remove it.
The query should be:
Debug() << query.prepare("INSERT INTO glucose(value, date, time, duration, note)
VALUES(?, ?, ?, ?, ?)");

Problem with % n *** %n in writable segment detected *** C++ i Qt

Problem with % n * %n in writable segment detected * C++ i Qt
I have program that process big data, that can't be modified. In one file we encounter "100% na" and application stop.
When I checked it with debuger, it return * %n in writable segment detected *.
I can't change visible that data, user must see "100% na". I thought of inserting some whitespace other then space after %.
Rewriting the whole applications is not a point. It runs on Windows and Linuks.
Currently the problem is in this code. I checked this in other places and it was the same. The variables are QStrings.
QSqlQuery query;
query.exec("insert into table_name ("+variable_with_columns_names+" values ("+variable_with_data_to_insert+");");
Do you have any ideas how to evade it?
edit
Prepare the query solved the problem in this spot. But it is breaking in others points. Update , Select ... where ...='100% na'(as variable), generating reports and other stuff. Whats more that this data is used by at least 5 modules, each using more then 5 data tables. So I will wait sometime, if anyone have other solution.
PS. One more question:
Why is "% n" interpreted as "%n", when it shouldn't?
Funny thing is if I change "100% na" to "100%% na", I get in data base "100%% na" when it should be changed to "100% na".
Use prepare to prepare the query. Then insert the values using bindValue. Prepared statements should always be used in such scenarios, as they handle the escaping of special characters for you.
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (?, ?, ?)");
query.bindValue(0, 1001);
query.bindValue(1, "Bart");
query.bindValue(2, "Simpson");
query.exec();
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (?, ?, ?)");
query.addBindValue(1001);
query.addBindValue("Bart");
query.addBindValue("Simpson");
query.exec();
any of these help?