Cannot copy one table to another? - python

I am using python to copy one table (dictionary) to another (origin_dictionary) in SQLite, and here is my code to this part:
def copyDictionaryToOrigin(self):
dropTableQueryStr = "DROP TABLE IF EXISTS origin_dictionary"
createTableQueryStr = "CREATE TABLE origin_dictionary (id INTEGER PRIMARY KEY AUTOINCREMENT, word TEXT, type TEXT)"
syncTableQueryStr = "INSERT INTO origin_dictionary (word, type) SELECT word, type FROM dictionary"
self.cur.execute(dropTableQueryStr)
self.cur.fetchone()
self.cur.execute(createTableQueryStr)
result = self.cur.fetchone()
self.cur.execute(syncTableQueryStr)
result = self.cur.fetchone()
With running this code, I can see a origin_dictionary table is created, but there is no data in the table. I could not find out the reason why the data didn't copy over to the new table. can someone please help me with this?

If you need to simply copy one table to another, why don't you use CREATE TABLE ... AS SELECT? Also, you need to commit() your statements.
Simply use code below, and it should work:
import sqlite3
conn = sqlite3.connect(example.db")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS origin_dictionary")
cur.execute("CREATE TABLE origin_dictionary AS SELECT * FROM dictionary")
conn.commit()
conn.close()

Related

Create SQLite Table With Variable

I want to create three tables fremdgehen.com, molligundwillig.de and reifer6.de.
But I am not able to transfer each element to CREATE TABLE. Why?
import sqlite3
con = sqlite3.connect('emails.db')
cur = con.cursor()
pages = ['fremdgehen.com', 'molligundwillig.de', 'reifer6.de']
for i in pages:
try:
sql_command = f'''
CREATE TABLE {i} (
email INTEGER,
password VARCHAR,
PRIMARY KEY (id));
cur.executescript(sql_command)
con.commit()
'''
except:
pass
con.close()
Since the table names contain a . character, you have to escape the names.
sql_command = f'''
CREATE TABLE `{i}` (
email INTEGER,
password VARCHAR,
PRIMARY KEY (id));
cur.executescript(sql_command)
con.commit()
'''
Note that having . in table and column names is inconvenient, because . is the separator between database, table, and column names. So you'll have to escape the table name in all your queries. Consider removing the . before using it as a table name to simplify this.

Delete values from db2 table if exist in schema in Python

i want to ask for a little help about my problem. I have sql query that get all the tables from some schema and put those tables in a list in Python. For example:
tablesList = ['TABLE1','TABLE2',...]
After i get this list of tables that i want i go one more time through each table in a for loop for example:
for t in range(len(tables)):
table = tables[t]
...
#here i want to check if this table exist in some db2 schema and if exist delete content
#of this table, otherwise go with next table check and don't delete content
Query for checking will be:
sql = """SELECT COUNT(*) FROM SYSIBM.SYSTABLES
WHERE TYPE = 'T'
AND CREATOR = 'MY_SCHEMA'
AND NAME = '{table}';""".format(table = table)
cursor.execute(sql)
rows_count = cursor.fetchone()
if rows_count is None:
pass
else:
delete...

sqlite3 insert not committing

When trying to insert rows into a table with a unique index, it appears to simply silently not insert.
I've captured the behaviour in the following program: on the second call to test_insert I should get an integrity violation on the unique key. But nothing. Also, if I take the c.execute(query, [id_to_test]) line and duplicate itself below it, I do receive the proper integrity constraint as expected. What's happening here?
import sqlite3
def test_insert(id_to_test):
conn = sqlite3.connect('test.db')
c = conn.cursor()
query = '''INSERT INTO test(unique_id)
VALUES(?)'''
c.execute(query, [id_to_test])
def setup_table():
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''DROP TABLE IF EXISTS test''')
c.execute('''CREATE TABLE test (unique_id text)''')
c.execute('''CREATE UNIQUE INDEX test_unique_id ON test (unique_id)''')
if __name__ == '__main__':
setup_table()
test_insert('test_id')
test_insert('test_id')
test_insert('test_id')
At the end of database operations, commit the changes to the database:
conn.commit()

How to get columns from a query in python?

I have that query in a python program:
And i should create a multidimensional array (if it possible) or four arrays from this query for every column from the query.
Can you suggest an elegant way to solve it?
conn = #connection to the server
cursor=conn.cursor()
query = (" select id, name, phone, city from guest")
cursor.execute(query)
results = cursor.fetchall
for i in results:
print i
cursor.close()
conn.close()
Not elegant but it may assist to unravel the mysterious Python Connector Cursor Class and transfers the list of tuples (see Copperfield comment) with the data from the query, into a list (phoneList) of dictionaries (entries) with details of each entry in the database, that might be easier to work with in your python script:
# ref: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html
import mysql.connector
db = 'test'
table = 'phonebook'
phoneList = []
drop_table = ("DROP TABLE IF EXISTS {};").format(table)
# By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
# To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
# ALTER TABLE phonebook AUTO_INCREMENT=100;
create_table = ("CREATE TABLE {} ("
"id int NOT NULL AUTO_INCREMENT,"
"name varchar(30) NOT NULL,"
"phone varchar(30) NOT NULL,"
"city varchar(30) NOT NULL,"
"PRIMARY KEY (id))"
" ENGINE=InnoDB DEFAULT CHARSET=latin1;").format(table)
Names = {'Bill':{'phone':'55123123','city':'Melbourne'},
'Mary':{'phone':'77111123','city':'Sydney'},
'Sue':{'phone':'55888123','city':'Melbourne'},
'Harry':{'phone':'77777123','city':'Sydney'},
'Fred':{'phone':'88123444','city':'Yongala'},
'Peter':{'phone':'55999123','city':'Melbourne'}}
cnx = mysql.connector.connect(user='mysqluser', password='xxxx',host='127.0.0.1',database=db)
cursor = cnx.cursor(dictionary=True) # key to using **row format
cursor.execute(drop_table)
cursor.execute(create_table)
# populate db
for name,detail in dict.items(Names):
sql = ("INSERT INTO {} (name,phone,city) VALUES ('{}','{}','{}')".format(table,name,detail['phone'],detail['city']))
cursor.execute(sql)
sql = ("SELECT id,name,phone,city FROM {}".format(table))
cursor.execute(sql)
for row in cursor:
print("{id} {name} {phone} {city}".format(**row))
phoneList.append(row)
print phoneList[0]['name'],phoneList[0]['city']
print phoneList[3]['name'],phoneList[3]['phone']
for entries in phoneList: # list of dictionaries
print entries['name'],entries
for entries in phoneList:
for k,v in dict.items(entries):
print k,v
print "\n"
cnx.close()

"No such column" when checking for table column

I am creating a table to add data to a database but I am not sure where to create the column for 'emails'. My final aim for this is to be able to enter a username (email) and password and for it to be saved into a database but I am not sure how to do this. Here is my code currently:
import sqlite3
def save_to_database(my_stack, filename = 'stack_database.db'):
conn = sqlite3.connect(filename)
c = conn.cursor()
for row in c.execute('SELECT email FROM sqlite_master WHERE type="table"'):
if row != None:
c.execute("DROP TABLE emails")
c.execute("CREATE TABLE emails(email text,login_date text)")
...
The sqlite_master table does not have a column named email; the entire table structure is contained in the text in the sql column.
You could check for the table name itself (but note that if no row is found, no row is returned, not even an empty one, so it does not make sense to try to handle this with a for loop):
c.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'emails'")
if not c.fetchall():
c.execute('DROP TABLE emails')
However, there is an easier method to ensure that a table is removed, regardless of its previous state:
c.execute('DROP TABLE IF EXISTS emails')

Categories