Write a python function that takes the name of a SQL table as parameter and then
ID: 3842349 • Letter: W
Question
Write a python function that takes the name of a SQL table as parameter and then does the following: Select all rows from that table (you can assume that the table already exists in SQLite) with all attributes from that table and output to a file a sequence of corresponding INSERT statements, one for each row from the table. Think of this as an export tool, since these INSERT statements could now be executed in Oracle (you do not need to actually execute them in Oracle that).
For example: generateInsertStatements('Students') should write to a file an insert statement from each row contained in the Students table (assuming the table is in SQLite already)
inserts.txt:
INSERT INTO Students VALUES (‘1’, ‘Jane’, ‘A-‘);
INSERT INTO Students VALUES (‘1’, ‘Mike’, ‘B‘);
INSERT INTO Students VALUES (‘1’, ‘Jack’, ‘B+‘);
Hint: as you iterate through the rows of the given table, instead of printing the output, you will want to write an INSERT SQL statement to an output file each time.
Explanation / Answer
import sqlite3
import os
def createFile(table):
database = raw_input(" Enter database name: ")
con = sqlite3.connect(database) #Connecting to the database
print "Opened database."
sql = 'SELECT * FROM ' + table #sql select statement
cursor = con.execute(sql) #executing sql statement
#opening file
insert = open('inserts.txt', 'w')
#iterating through each record row
for record in cursor:
#creating insert statement
sql = 'INSERT INTO ' + table + ' VALUES ('
#for all columns in the row
for column in record:
sql = sql + "'" + column + "',"
sql = sql.rstrip(',') + '); '
insert.write(sql) #writing into file
insert.close() #closing and saving file
con.close() #closing connection
createFile('Students')
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.