Import PostgreSQL Values to SQLITE
Hi everybody,
I am trying to make a function that import data from a table from PostgreSQL and insert the data on a sqlite3 database.
But i dont know if my idea will work, can somebody help me:
Code:
bool MainWindow::connectToDB()
{
db.setHostName("localhost");
db.setDatabaseName("lernit");
db.setUserName("admin");
db.setPassword("admin");
if(!db.open())
{
QMessageBox::information(this,
"LenrIT",db.
lastError().
text());
}
else
{
QSqlQuery select
("SELECT language1, language2, plural, description FROM words_tbl");
while(select.next())
{
QString language1
= select.
value(0).
toString();
QString language2
= select.
value(1).
toString();
QString plural
= select.
value(2).
toString();
QString description
= select.
value(3).
toString();
db2.setDatabaseName("LernIT.db");
if(!db2.open())
QMessageBox::information(this,
"LenrIT",db.
lastError().
text());
insert.prepare("insert into words_tbl (language1, language2, plural, description) values ('"
+ language1 + "', '" + language2 + "', '" + plural + "', '" + description + "')");
if( ! insert.exec() )
QMessageBox::information(this,
"LernIT",insert.
lastError().
text());
db.setHostName("localhost");
db.setDatabaseName("lernit");
db.setUserName("admin");
db.setPassword("admin");
if(!db.open())
QMessageBox::information(this,
"LenrIT",db.
lastError().
text());
}
}
}
Re: Import PostgreSQL Values to SQLITE
You dont know if it will work ? Run it ;)
Why you create second handler to posgre database ?
Re: Import PostgreSQL Values to SQLITE
Quote:
Originally Posted by
raphaelf
QSqlDatabase db2 = QSqlDatabase::addDatabase("QSQLITE");
It should be:This way you will create a second connection, without closing the first one, so you won't have to connect to the database every time you want to insert something.
Quote:
Originally Posted by
raphaelf
QSqlQuery insert;
This should be:because you want to use that other connection for this statement.
Quote:
Originally Posted by
raphaelf
insert.prepare("insert into words_tbl (language1, language2, plural, description) values ('"
+ language1 + "', '" + language2 + "', '" + plural + "', '" + description + "')");
This is dangerous, better use bindValue():
Code:
insert.prepare("insert into words_tbl (language1, language2, plural, description) values ( :lang1, :lang2, :plural, :desc )" );
insert.bindValue( ":lang1", language1 );
...
This way you can also optimise your code a bit by invoking insert.prepare() only once.
Your code should look like this:- open connection to PostgreSQL
- open connection to SQLite
- prepare the insert statement
- prepare the select statement
- execute the select statement
- for each selected row:
- bind values to the insert statement
- execute the insert statement