QSqlQuery causing ODBC Function sequence error - c++

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

Related

how to connect sql server database in C++ code?

I have a project of C++ windows form. Now, I want to store the data in my SQL server database.
So, how can I connect my database from inside my C++ code and how to write an insert query?
I used the following code but it throws an exception that cannot open or cannot found the database.
SqlConnection^ con = gcnew SqlConnection();
int i = 0;
con->ConnectionString = "Data Source=122.179.151.229\EIEXPRESS;Initial Catalog=ICAST_IMS;Uid=developer;pwd=dev#12345";
con->Open();
SqlCommand^ com = gcnew SqlCommand();
com->Connection = con;
com->CommandText = "INSERT INTO image_analysis (nodule_count, nodularity) VALUES (final_nodule_count, 'final_nodularity')";
com->ExecuteNonQuery();
I think your problem it's your connection string, you include an "\" which is a special character, you need to try doing "\\" so the system recognize you're inserting an "\".
Hope this helps you!

"Unable to find table" error when calling QSqlTableModel setTable method

I need to populate a QTableView by retrieving data from a QSqlTableModel object. I use following commands to make a connection to a sql server database:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectionTemplate = "DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Uid=username;Pwd=password;Trusted_Connection=Yes;";
QString connectionString = connectionTemplate.arg("localhost").arg("mydb");
db.setDatabaseName(connectionString);
I validate the database connection by the methods isValid() and open() from QSqlDatabase class. I am also able to query from the database tables properly. ٍEvery thing is ok so far. But the problem arises when I use following commands:
QSqlTableModel* model = new QSqlTableModel(parent,db);
model->setTable("mytable");
qDebug() << model->lastError().text(); // the error message is printed on consul.
The method setTable not working and causes an error: Unable to find table \"mytable\".
I found the solution. I should open the database right after setDatabaseName and before creation of QSqlTableModel:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString connectionTemplate = "DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Uid=username;Pwd=password;Trusted_Connection=Yes;";
QString connectionString = connectionTemplate.arg("localhost").arg("mydb");
db.setDatabaseName(connectionString);
db.open(); // :)
QSqlTableModel* model = new QSqlTableModel(parent,db);
model->setTable("mytable");
According to http://doc.qt.io/qt-5/qsqltablemodel.html#QSqlTableModel
the constructor of QSqlTablemodel:
Creates an empty QSqlTableModel and sets the parent to parent and the
database connection to db. If db is not valid, the default database
connection will be used.
In the event that your db object is not valid you would connect to a default database where your table is not available.
Double check the parameters used to initialize and setup QSqlDatabase db.

Can't retrieve identity field after insert in sql database

Using C++ Qt framework and sql server 2008 I've been trying to insert a record into a table with an identity field and retrieve the identity value. Below is a simplified code sample which actually does do the insert but just doesn't retreive the identity. The identity returned from query.value(0) is an invalid QVariant.
QSqlQuery query(*pConn);
query.prepare("insert into [VH_MANUFACTURER] values ('sRRS test man code','RRS type','RRS logo file',1,'RRS SEO para','RRS description','RS');"
"select SCOPE_IDENTITY();");
if(query.exec())
{
if(query.next())
{
QVariant identity = query.value(0);
int id=identity.toInt();
}
}
I've tried using select ##identity instead of scope_identity with no improvement and also QSqlQuery .lastInsertId() which also returns an invalid QVariant, see below.
bool bFeature = pConn->driver()->hasFeature(QSqlDriver::LastInsertId);
QSqlQuery query(*pConn);
query.prepare("insert into [VH_MANUFACTURER] ([MFG_NAME],[MFG_TYPE],[MFG_LOGO],[MFG_ACTIVE],[MFG_SEO_CONTENT],[MFG_DESCRI],[MFG_CAPMANCODE]) values ('sRRS test man code','RRS type','RRS logo file',1,'RRS SEO para','RRS description','RS')");
if(query.exec())
{
QVariant id=query.lastInsertId();
}
hasFeature returns true, so the driver is supposed to support what I'm trying to do.
Just to test the sql , I ran the sql directly through Sql Server Management Studio and it inserts as expected and returns the identity value correctly.
Finally found a work around using OUTPUT clause in sql. I don't exactly know why the other methods I tried don't work. There is a sql server bug associated with this feature but that doesn't explain why it worked in ssms but not in c++ Qt code. The sample below show's the work around. Here's the reference I used to solve this.
bool bFeature = pConn->driver()->hasFeature(QSqlDriver::LastInsertId);
QSqlQuery query(*pConn);
query.prepare("insert into [VH_MANUFACTURER] ([MFG_NAME],[MFG_TYPE],[MFG_LOGO],[MFG_ACTIVE],[MFG_SEO_CONTENT],[MFG_DESCRI],[MFG_CAPMANCODE]) OUTPUT INSERTED.MFG_ID values ('sRRS test man code','RRS type','RRS logo file',1,'RRS SEO para','RRS description','RS')");
if(query.exec())
{
if(query.next())
{
QVariant id=query.value("MFG_ID");
}
}

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.

can not make a table in sqlite3 by Qt

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.