Life is hard, when you are learning Python and you see things that are making no sense the way they run. After writing about adding data to SqlLite3 with Python, today I have tried to do the same, but for one column only. In general, this should be a piece of cake – just remove the second column and enjoy. However, it was not that easy, as far as I somehow realized that Python was allowing to add only 1 letter of the request.
Thus, the following piece of code:
1 2 3 4 |
topics = [("JavaScript"), ("C#"), (".NET")] sql_command = """INSERT INTO %s (%s) VALUES (?)""" % (table_name, column_name) cur.executemany (sql_command, topics) conn.commit() |
was returning the nice error below, stating obviously that the JavaScript input was considered to be 10 bindings, 1 for each word:
Where was the problem. After too much debugging (more than I would be ever willing to admit), I have found out the problem was in the way the tuple was passed. E.g., if you want to pass a list of tuples, inform python it is a list of tuples, otherwise it takes it for something else. Thus, this is the correct way to do it (the comma is important):
1 |
topics = [("VBA",), ("C#",), (".NET",)] |
And it nicely works. The whole code, including creating and table in the database is here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import sqlite3 def main(): conn = sqlite3.connect(r"C:\Users\vitos\Desktop\db\my.db") cur = conn.cursor() table_name = "articles" column_name = "Title" drop_table_if_exists(table_name, cur,conn) sql_command = """ CREATE TABLE %s ( Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, %s TEXT ) """ % (table_name, column_name) cur.execute(sql_command) topics = [("VBA",), ("C#",), (".NET",)] sql_command = """INSERT INTO %s (%s) VALUES (?)""" % (table_name, column_name) cur.executemany (sql_command, topics) conn.commit() def drop_table_if_exists(table_name, cur, conn): sql = "DROP TABLE IF EXISTS %s" % table_name cur.executescript(sql) conn.commit() if __name__== "__main__": main() |
Enjoy it!