Monday, May 23, 2011

Qt and SQlite Database Basics

1.Add this into .pro file:

QT += core gui sql

2.Add this headers

#include QSqlDatabase
#include QtSql
#include Qtdebug

3.Add this code

QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );

db.setDatabaseName( "nameAge.db");

if( !db.open() )
{
qDebug() << db.lastError();
qFatal( "Could not find db.");
}

qDebug( "Connected!" );

QSqlQuery qry;

qry.prepare( "CREATE TABLE IF NOT EXISTS people ( name string, age integer)" );
if( !qry.exec() )
qDebug() << qry.lastError();
else
qDebug() << "Table Created";

/*qry.prepare( "INSERT INTO people VALUES ('Momontar',56)" );
if( !qry.exec() )
qDebug() << qry.lastError();
else
qDebug() << "Momontar Values inserted";*/

qry.prepare( "SELECT * FROM people");
if( !qry.exec() )
qDebug() << qry.lastError();
else
{
qDebug( "Selected success");

QSqlRecord rec = qry.record();

int cols = rec.count();

for( int c = 0; c qDebug() << QString( "Column %1: %2").arg( c ).arg( rec.fieldName(c) );

for( int r = 0; qry.next(); r++ )
for( int c=0; c qDebug() << QString( "Row %1, %2: %3").arg( r ).arg( rec.fieldName(c) ).arg( qry.value(c).toString() );

}

4.You'll find the nameAge.db in the projectName-Build folder.

No comments:

Post a Comment