can not make a table in sqlite3 by Qt - c++

i have made a database in terminal by this command:
sqlite3 test.db
then i tried to make a table by using these codes:
ui->setupUi(this);
db1.setDatabaseName("test.db");
bool k=db1.open();
QSqlQuery q(db1);
q.prepare("CREATE TABLE by_code(id INT)");
q.exec();
qDebug()<<"isOpen: "<<k<<" Error:"<<q.lastError();
the output is :
isOpen: true Error: QSqlError(-1, "Unable to fetch row", "No query")
whats problem and how can i solve it?

Qt tried to get the result of the query, but a CREATE TABLE statement does not return a result.
This is not considered an actual error.
To check whether the query succeeded, check the return value of the exec function.

Related

QSqlQuery causing ODBC Function sequence error

I searched SO and Google but didn't find much help on this question. It seems due to ODBC functions being called out out of order. But since I am using QSql that wraps ODBC, it is hard for me to track down the function. Please help...
I was able to connect to the sql server database
I tested a very simply query and still got the error. I don't think it's due to column binding.
I was able to run the query with sql server, so I think the sql query is ok.
The tools I am using:
VS c++ 2017, CMake, Qt 5.09.2, sql server 2017
Below are the error messages:
QODBCResult::exec: Unable to execute statement: "[Microsoft][ODBC Driver Manager] Function sequence error"
QSqlError("0", "QODBC3: Unable to execute statement", "[Microsoft][ODBC Driver Manager] Function sequence error")
Test coding:
This coding generate the error message above.
int main()
{
QSqlDatabase GUIInpDB = QSqlDatabase::addDatabase("QODBC", "MainSQLDB");
GUIInpDB.setConnectOptions();
QString inpSqlServer = "DESKTOP-085AEA8\\SQLEXPRESS";
QString dbName = "test";
QString connString = QString("Driver={ODBC Driver 13 for SQL Server};Server=%1;DATABASE=%2;Trusted_Connection=Yes;")
.arg(inpSqlServer).arg(dbName); //the argument replace the %1 and %2
GUIInpDB.setDatabaseName(connString);
QSqlDatabase db = QSqlDatabase::database("MainSQLDB");
if (!db.open())
{
qDebug() << "Connection for db not working";
return 1;
}
QSqlQuery query("SELECT * FROM TBL.tbl_test", db);
if (!query.exec())
qDebug() << query.lastError();
int num_of_rows = query.size();
getchar();
return 0;
}
I found this discussion on QtCenter that might help you, even if I am doubtful about why it fixed the issue
You migth try to use the QSqlQuery constructor that does not exec as mentionned
http://www.qtcentre.org/threads/18832-ODBC-function-sequence-error

Qt Parameter Count Mismatch with QSQL and Bind Values

I'm currently facing an error where I get "Parameter count mismatch" from query.lastError, my bindvalues are correct (i've tested them).
My query is:
QSqlQuery query(DBT);
query.prepare("SELECT Foto, Nombre, Apellido1, Apellido2, Curso, Grupo, FotoHuella FROM usuarios WHERE Nombre=:nombre1 OR Apellido1=:apellido1 OR Apellido2=:apellido2 OR Curso=:curso1 OR Grupo=:grupo1");
query.bindValue(":nombre1", nombre, QSql::Out);
query.bindValue(":apellido1", apellido1, QSql::Out);
query.bindValue(":apellido2", apellido2, QSql::Out);
query.bindValue(":curso1", curso, QSql::Out);
query.bindValue(":grupo1", grupo, QSql::Out);
query.exec();
In case you where wondering here is where I set up the database:
QSqlDatabase DBT=QSqlDatabase::addDatabase("QSQLITE");
DBT.setDatabaseName("/home/pi/FoodCircleDBT.db");
DBT.open();
Thanks in advance.
Solution for me: actually everything relating to the code worked perfectly but somehow my database schema went crazy when I edited it with a database program. So If you are facing this I recommend you to open the command line and checking your schema.

Qt and SQLite, error when executing query, without error message

I am using Qt 5.4 and SQLite to to database operations, all other requests work, but this one doesn't seem to work and gives no error.
QSqlQuery query(Globals::db);
QString cmd = "Update VideoFile set isVisible = 0 WHERE Id =1;";
if(query.prepare(cmd))
qDebug("Prepare success..."); //<-- prints out
if (!query.exec()) {
qDebug("Error occurred querying.");
qDebug("%s.", qPrintable(Globals::db.lastError().text())); //<<-- prints out blank
}
Tried so far:
o) Database: exists!
o) Query Prepare() yields True
o) When executing the same Statement in SQLite Browser. Works!
i read about a problem here:, that some databases have a certain delay.
"Portability note: Some databases choose to delay preparing a query until it is executed the first time. In this case, preparing a syntactically wrong query succeeds, but every consecutive exec() will fail." But apparently, the query is not syntactically wrong.

QSqlDatabase::open() always returns true

i'm trying to connect to a sql database with the Qt-Framework.
Unfortunately db.open() always returns true (you can set any password, hostname, etc...), despite no connection is established(?). I derive that from the query not having any effect on the database.
I'm using LAMPP on Ubuntu 14.04.
I've got the following code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QSql>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlQuery>
void MainWindow::on_ButtonSQL_clicked()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "con1");
db.setHostName("localhost");
db.setDatabaseName("kinectshop2015");
db.setUserName("root");
db.setPassword("");
QMessageBox msgBox;
if (db.open()) {
msgBox.setText("Yay! Your database host is "+db.hostName()+" .\n"+" The name of the database is "+db.databaseName()+".");
msgBox.exec();
}
QSqlQuery query;
query.exec("INSERT INTO users (id, username, balance, isAdmin)" "VALUES(3, 'somebody', 10000, 1)");
}
One problem is that you are specifying a connectionName.
QSqlDatabase QSqlDatabase::addDatabase(const QString & type, const QString & connectionName = QLatin1String( defaultConnection ))
If connectionName is not specified, the new connection becomes the default connection
Given that your db connection is not the default connection, you need to tell the QSqlQuery which db to use, i.e.
QSqlQuery query(db);
query.exec("INSERT INTO users (id, username, balance, isAdmin)" "VALUES(3, 'somebody', 10000, 1)");
The other 'problem' is that with sqlite you always create a new database by the call you are making, thus the problem is not that the DB is not open but that its contents are not right (since it will be empty if you specify a non existing filename). If I take your code and add
qDebug() << query.lastError();
after the query.exec it rightfully complains that
QSqlError(1, "Unable to execute statement", "no such table: users")
If I include a statement to create the table before the insert query
QSqlQuery createTable("create table users ( id INTEGER, username TEXT, balance REAL, isAdmin INTEGER)",db);
createTable.exec();
I correctly get the table in the newly create db file and it has the entry that you are trying to insert.
Does this help?
Here is what solved my problem. I used the driver QMYSQL instead of QSQLITE. I had only used the latter, because the first one couldn't be loaded. On Ubuntu & QT5 simply type sudo apt-get install libqt5sql5-mysql to resolve the problem.

Correct way to use QVariant when extracting data from a database

I have recently begun working with QT and I'm having a small issue. I cant seem to understand how QVariant works. I've been going through the help and looking online but it is just not sinking in. In my project i am trying to populate a combo box with a list of manufacturers from a database. I have opened the database and pulled out the entries but I rename them all manValue. Now I understand why this is happening, the problem is I do not understand how to properly use QVariant to get the result I want. Originally i thought "manValue" was going to be the identifier for the string that held the actual value from the database but instead it reads the value from the database and makes sure it is not null, and then renames it. I already tried making a string before I assign the QVariant with any properties and assigning it the text i received from the database, and then inserting that string where manValue is but still no luck. Any help would be greatly appreciated. Sorry, I know this is going to be simple I'm just a noob and the help docs often confuse me.
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName("LOCALHOST\\TestERPServer");
db.setDatabaseName("TestERPConnection");
if (db.open())
{
QMessageBox::information(this,"Connected","Connection to the Database was Established\n"
"\nStatus: Connected");
QSqlQuery mfrQry;
if (mfrQry.exec("SELECT * FROM erp_data.manufacturers;"))
{
if (mfrQry.value(1) == "")
{
QMessageBox::information(this,"No Connection","Nothing in the Manufacturer Database\n"
"\nError: " + db.lastError().text());
}
else
{
while (mfrQry.next())
{
ui->mfrComboBox->addItem("manValue",QVariant(mfrQry.value(1)));
}
}
}
else
{
QMessageBox::information(this,"No Connection","Connection to the Manufacturer Database could not be Established\n"
"\nError: " + db.lastError().text());
}
}
else
{
QMessageBox::information(this,"No Connection","Connection to the Database could not be Established\n"
"\nError: " + db.lastError().text());
}
The first problem in the provided code has to do with the way you manipulate the QSqlQuery.
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. In either case, when executing a new SQL statement, the
query is positioned on an invalid record. An active query must be
navigated to a valid record before values can be retrieved.
In order to move to a valid record you have to use one of the following:
next()
previous()
first()
last()
seek()
Once you are on a valid record you have to use the value() function in order to take the column you want. The returned value is QVariant so you need to convert to the desired type using one of the many toSomething functions QVariant provides.
So in your case the code should look like this:
QSqlQuery mfrQry;
if (mfrQry.exec("SELECT * FROM erp_data.manufacturers;"))
{
// This will loop through all records returned by the query
while (mfrQry.next()) {
// mfrQry.value(COLID) returns a QVariant containing the data of the current
// record in column COLID.
// Using toString we convert it to String
QString stringValue = mfrQry.value(COLID).toString();
// Now handle the QString the way you want...
}
}