Reputation: 760
I was wondering what the best method is for transfer data from a qtablewidget
to an SQLite database and if im on the right try if you could help me find a way to generate some SQL code. I am making a program to keep track of current projects or my company and I have a GUI with a table that a user will add data too. I would like to be able to transfer that data into a database. So far the best method I can think of is to loop through the table to get all the values and then when it is finished then have it generate code to send to the database. The problem I'm having is I'm not sure how to generate the SQL code at the end. I have working code to connect to my database and my table, but just generating the code that goes in the VALUE
db_filename = '.\DB\ProgramManagerDB.sqlite'
with sqlite3.connect(db_filename) as conn:
cursorProject = conn.cursor()
cursorProject.execute(""" INSERT INTO contacts(Name,Number,title,company,email,main_contact) VALUES (?,?,?,?,?,?)""",(This is what im not sure how to generate))
Is there a better way of doing this or is that the most efficient way of doing it? Thank you for your help and advice.
Code for looping through table and getting values
for i in range(0,self.AddProjects.tableWidget_Contacts.rowCount()):
contactName = self.AddProjects.tableWidget_Contacts.item(i,0).text()
contactNumber = self.AddProjects.tableWidget_Contacts.item(i,1).text()
title = self.AddProjects.tableWidget_Contacts.item(i,2).text()
company = self.AddProjects.tableWidget_Contacts.item(i,3).text()
email = self.AddProjects.tableWidget_Contacts.item(i,4).text()
mainContact = self.AddProjects.tableWidget_Contacts.item(i,5).text()
Upvotes: 2
Views: 1772
Reputation: 438
Assuming everything else is good to go, try using "append" here:
cursorProject.execute(""" INSERT INTO contacts(Name,Number,title,company,email,main_contact) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')""".append(contactName, contactNumber, title, company, email, mainContact) )
Note: You may want to generate the SQL first as a string, then pass it to .execute(), or you may want to pass those values as a parameter if your particular sql supports it.
Note 2: There may be more efficient ways to do what you're attempting, but this looks like a great start!
Upvotes: 1