PDA

View Full Version : How to insert certain table_1 column value in table_2



Lalremruata
23rd June 2021, 03:37
I am stuck and request help. I have an Sqlite3 table and code with PyQt5 in PyCharm. I want to insert id's latest row of table_1 into a "import" column in table_2 simultaneously when a button is click to make new record for/in table_2. [Fetch table_1 id's latest row number and insert into "import" column along with name1 and name2 (user input) text value in table_2 when a button is click.]

Table_1:
CREATE TABLE "table_1" (
"id" INTEGER UNIQUE,
"first_name" TEXT,
"last_name" TEXT,
PRIMARY KEY("id" AUTOINCREMENT)
)

Table_2:
CREATE TABLE "table_2" (
"import" INTEGER,
"name1" TEXT,
"name2" TEXT
)

I have google many website but could not find clue/answer to my problem. There are some code to insert value(s) into another table but they missed out on how to insert into along with capturing the QlineEdit user's input values.

Thanks in advance.

ChrisW67
25th June 2021, 05:44
I am stuck and request help. I have an Sqlite3 table and code with PyQt5 in PyCharm. I want to insert id's latest row of table_1 into a "import" column in table_2 simultaneously when a button is click to make new record for/in table_2. [Fetch table_1 id's latest row number and insert into "import" column along with name1 and name2 (user input) text value in table_2 when a button is click.]


How do you insert the row into table_1? Using a QSqlQuery or QSqlTableModel or something else?

Lalremruata
27th June 2021, 02:45
By means of QSqlQuery

ChrisW67
28th June 2021, 08:22
By means of QSqlQuery

First you should read this (https://www.sqlite.org/autoinc.html) and this (https://www.sqlite.org/c3ref/last_insert_rowid.html)

Then your code works something like this:


QSqlDatabase db = QSqlDatabase::database(); // I am assuming default database connection

QSqlQuery qry1;
qry1.prepare("insert into table_1(first_name, last_name) values (:first_name, :last_name)");
QSqlQuery qry2;
qry2.prepare("insert into table_2(import, name1, name2) values (last_insert_rowid(), :name1, :name2)" );

if (db.transaction()) {
bool success = false;
qry1.bindValue(":first_name", ui->lineEdit1->text());
qry1.bindValue(":last_name", ui->lineEdit2->text());
if (qry1.exec()) {
qry2.bindValue(":name1", ui->lineEdit3->text());
qry2.bindValue(":name2", ui->lineEdit4->text());
if (qry2.exec()) {
success = true;
}
}
if (success) {
db.commit();
}
else {
// SQL died for some reason
db.rollback();
}
}
else {
// error could not start transaction
}