How to check database is exist or not? - c++

I am using sqlite database in qt. Database created when i use setDatabase("") function. But i dont know how to check same database is exist or not. Here is my code:
//add database driver
db = QSqlDatabase::addDatabase ("QSQLITE");
//create database
if(db.databaseName () == db_Name){
qDebug() << "Database exist or not created." << endl;
} else {
db.setDatabaseName (db_Name);
qDebug() << "Database created." << endl;
}
//opening connection
db.open ();
//if connection created
if(db.isOpen ()){
qDebug() << "Database connected." << endl;
} else {
qDebug() << "Database not connected." << endl;
}
I get the Database created. message. How to check ? Thanks.

You can simply check the database file whether it exists using QFile:
if (QFile::exists(db_Name)) {
// database exists
}

SQLite creates an empty database when you try to open a nonexisting file.
So if you want to know if you need to create the tables for your application, just run a query to check whether these tables exist:
SELECT * FROM sqlite_master WHERE name = 'MyTable';

Related

QSqlTablelModel cannot find SQL view, but QSqlQuery can

I want to use QSqlTableModel since it seems easier to use. It does however not find my tables.
qDebug() << "connecting";
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(dbHostName);
db.setPort(dbPort);
db.setUserName(dbUserName);
db.setPassword(dbPassword);
// Connect to database sys to get some info to test (basic communication)
db.setDatabaseName("sys");
// Check if opened and if so get some data
if(db.open()){
qDebug() << "DB succesfully opened";
} else {
qDebug() << "DB failed to open";
return;
}
QSqlTableModel* runsSimulationViewModel = new QSqlTableModel();
runsSimulationViewModel->setTable("results.runs_simulation_view");
qDebug() << runsSimulationViewModel->lastError();
//ERROR: QSqlError("", "Unable to find table results.runs_simulation_view", "")
QSqlQuery anotherQuery;
anotherQuery.prepare("SELECT * FROM results.runs_simulation_view");
if(!anotherQuery.exec()) {
qDebug() << anotherQuery.lastError();
} else {
anotherQuery.next();
qDebug() << anotherQuery.value("simulation_id").toInt();
//Prints "3", which is the first value for this field in the table
}
QSqlQuery works, but QSqlTableView cannot find this (SQL) view (and also no tables).
What am I missing?

MySQL in C++ Seg Fault

I'm implementing mySQL in C++ and ran into an issue. I'm getting a seg fault. And I'm not sure why.
Was hoping someone would know what is going on.
The seg fault seems to be happening somewhere after the MYSQL_ROW productList; line, I haven't been able to pin point where though.
void Receiving::getProduct(const string productToReturn) {
MYSQL *connect, mysql; //Pointers to MySQL
connect = mysql_init(&mysql); // Initialize the connections
int totalRows = 0;
connect = mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0); //Connect to database
if(connect) { //If connection successful
string sqlQuery; //will hold query
MYSQL_RES *resSetProduct; //define product result set
MYSQL_ROW productList; //define row for product
sqlQuery = "SELECT * FROM Inventory WHERE item_id = \' "; //Create query with desired product id
sqlQuery += productToReturn;
sqlQuery += " \'";
mysql_query(connect, sqlQuery.c_str()); // Send query to the database
resSetProduct = mysql_store_result(connect); // Receive the result and store it in resSetProduct
totalRows = mysql_num_rows(resSetProduct); // count of stored rows
if(totalRows == 0){ //nothing found
cout << "Sorry! No inventory found for that product!" << endl;
}
else {
cout << "Product Id In Stock" << endl;
while( (productList = mysql_fetch_row(resSetProduct)) != NULL ) { //printout the products
cout << productList[0] << " " << productList[1] << endl;
}
}
mysql_free_result(resSetProduct);
}
else //Failed to connect
cerr << "Failed To Connect!";
mysql_close(connect);
}
You should check if mysql_query returns zero. If it does not, mysql_store_result will return NULL and mysql_num_rows might fail with a segfault.
If mysql_query returns non-zero you can check the error codes according to the mysql documentation, eg. here: MySQL mysql_query
As soon as those errors are cleared, mysql_num_rows should not segfault anymore.

Catching SQL errors using Qt

The code below doesn't work for catching sql errors with Qt and sqlite. I've also tried isNull. I'm getting a blank string for lasterror.text() and -1 for error number with working queries. I don't understand why isEmpty or isNull aren't working.
if (!query.lastError().text().isEmpty())
{
logfile(sqlstatement);
logfile("SqLite error:" + query.lastError().text());
logfile("SqLite error code:"+ QString::number( query.lastError().number() ));
}
Do you really execute your query?
Take a look at way of doing access do SQLite DB + logging in OpenSource application Mixxx (Opening database, applying query):
...
#define LOG_FAILED_QUERY(query) qDebug() << __FILE__ << __LINE__ << "FAILED QUERY [" \
<< (query).executedQuery() << "]" << (query).lastError()
...
// Check if you have QSQLITE2/QSQLITE driver avaiable
qDebug() << "Available QtSQL drivers:" << QSqlDatabase::drivers();
m_db.setHostName(...);
m_db.setDatabaseName(...);
m_db.setUserName(...);
m_db.setPassword(...);
bool ok = m_db.open();
qDebug() << "DB status:" << m_db.databaseName() << "=" << ok;
if (m_db.lastError().isValid()) {
qDebug() << "Error loading database:" << m_db.lastError();
}
...
QSqlQuery query(m_database);
query.setForwardOnly(true);
query.prepare(queryString);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
And be sure that this works :)

Simple solutions for integrating MySQL with C++?

What solutions are there for making a simple connection to a MySQL database in C++?
I find MySQL Connector from dev.mysql.com hard to integrate.
Anticipated thanks!
Its pretty simple to communicate with MySQL from C/C++ application
you need to include mysql.h header file
three basic APIs to connect and execute query
mysql_connect()
mysql_query()
mysql_close()
Link with mysql library (libMysql)
You could try the ODBC path, with a support library.
Some year ago I used OTL to interface SqlServer and found it efficient. Now I've tried to interface MySql, without any problem so far:
#include <otlv4.h>
#include <iostream>
using namespace std;
int otl_x_sql_main(int argc, char **argv)
{
otl_connect db; // connect object
otl_connect::otl_initialize(); // initialize ODBC environment
try {
db.rlogon("DRIVER=mysql;DB=...;UID=...;PWD=..."); // connect to ODBC
// parametrized SELECT
otl_stream i(50, "SELECT product_id,model FROM product WHERE product_id >= :f<int> AND product_id < :ff<int>", db);
int product_id;
char model[100];
i << 1000 << 2000; // assigning product_id range
// SELECT automatically executes when all input variables are assigned
while (!i.eof()) {
i >> product_id >> model;
cout << "product_id=" << product_id << ", model=" << model << endl;
}
}
catch(otl_exception& p) { // intercept OTL exceptions
cerr << p.msg << endl; // print out error message
cerr << p.stm_text << endl; // print out SQL that caused the error
cerr << p.sqlstate << endl; // print out SQLSTATE message
cerr << p.var_info << endl; // print out the variable that caused the error
}
return 0;
}

mysql cpp connector throwing UnknownException while connecting

I am using mysql library to connect to my database (mysql) to retrieve the data after connecting. Checked that my services are running properly.
Following is the part of code that does the connecting task..
// Specify our connection target and credentials
const string server = "tcp://127.0.0.1:3306";
const string username = "root";
const string password = "";// No password - thanks, WAMP Server!
// Try to get a driver to use to connect to our DBMS
try {
driver = get_driver_instance();
if( driver == NULL )
throw SQLException("Null driver instance returned.");
}
catch (SQLException e) {
cout << "Could not get a database driver. Error message: " << e.what() << endl;
return -3;
}
// Try to connect to the DBMS server
try {
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e) {
cout << "Could not connect to database. Error message: " << e.getSQLStateCStr() << " Error Code: " << e.getErrorCode() << endl;
cout << "Could not connect to database. Error: " << e.what() << endl;
return -1;
}
It compiles well but gives an unknown exception with unknown debug info. Something like this. Please help.
This worked after changing the string to SQLString for all the connection params like server, username and password.
This worked out like a charm.