PDA

View Full Version : steps to connect to SQLite from Q



Qt Coder
2nd July 2009, 13:04
I m using Qt 4.4.3 on windows
I want to use SQLite database for my application.
I have installed SQLIte Maestro and created database.

could anyone tell me steps to connect to SQLite from Qt.......

do I need to configure any SQLite optins..??

lyuts
2nd July 2009, 14:26
Take a look at Qt examples. There is a fiile called "examples/sql/connection.h".

In your case you will have to specify a valid path to your db instead of ":memory:".

genessr
8th July 2009, 01:57
Try this.

// Declares a database object
QSqlDatabase db

// opens a database connection for sqlite database
db = QSqlDatabase::addDatabase("QSQLITE");

// creates/opens a database genes.db in home directory of your application.
db.setDatabaseName("genes.db");

SunnySan
8th July 2009, 12:12
Part example:




#define DBHOST "127.0.0.1" //for localhost loop
#define DBDRIVER "QSQLITE" //if use other DB need the driver with dll files
#define DBNAME "DB.db3" //name used for the database file
//#define

//constructor
Database::Database() {
createConnectiontoSqlite();
}
....

bool Database::createConnectiontoSqlite() {
QSqlDatabase db = QSqlDatabase::addDatabase(DBDRIVER);// changed "QSQLITE" with define DBDRIVER
db.setHostName(DBHOST);
db.setDatabaseName(DBNAME); //if the dababase does not exist he will create it
//the database name is also the name of the file in the working directory
// db.setUserName("user");//username and password does not affect SQLITE db
// db.setPassword("pass");

if (!db.open()) {
QMessageBox::critical(0, QObject::tr("DB Error - CreateConnection()"),
db.lastError().text());
return false;
}
return true;

}

void Database::createTables() {
QSqlQuery query;
//main Tables
// table
query.exec(
"create table table1(id int primary key, name varchar(20), variable int, company int)");
query.exec("insert into table1 values(1, 'Default', 1, 1)");
query.exec("insert into table1 values(2, 'blabla', 2, 1)");
.....


qDebug() << "dB created "; //need to set up debug in the .pro file



hope this help