Python SQLite insert statement executing but not inserting any data - python

Dear Stackoverflow community,
i have the following problem. I am using Python 3.5
and SQLite3 package and I'm trying to insert 20 cities into the city table of my database. The problem ist that after executing the code there is no error message but the entries won't show up in the database.
My Code looks like this
Database.py: this file encapsulates the database and provides the functionality to easily execute queries.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
from sqlite3 import Error
class Database:
database_connection = 0;
def __init__(self, path_to_database):
self.__try_connect__(path_to_database)
def __try_connect__ (self, path_to_database):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
self.database_connection = sqlite3.connect(path_to_database)
except Error as e:
print(e)
def execute_query(self, query):
database_cursor = self.database_connection.cursor()
print(database_cursor.execute(query))
def insert(self, table_name, assoziative_key_value_array):
print("insert not yet implemented")
DatabaseCreator.py: if you want to try to run my code you can use
this class that creates the database for you
from Database import Database
class DatabaseCreator:
database = 0
#staticmethod
def create(path_to_database):
database = Database(path_to_database)
DatabaseCreator.delete_old(database)
DatabaseCreator.create_new(database)
#staticmethod
def delete_old(database):
print("#DatabaseCreator - delete old")
database.execute_query("DROP TABLE 'Städte'")
database.execute_query("DROP TABLE 'Vereine'")
database.execute_query("DROP TABLE 'Präsidenten'")
database.execute_query("DROP TABLE 'Spieler'")
#staticmethod
def create_new(database):
print("#DatabaseCreator - create new");
database.execute_query("CREATE TABLE 'Städte' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL);")
database.execute_query("CREATE TABLE 'Präsidenten' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL);")
database.execute_query("CREATE TABLE 'Vereine' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL, 'Tabellenplatz' INTEGER NOT NULL, 'PräsidentId' INTEGER NOT NULL, 'StadtId' INTEGER NOT NULL, FOREIGN KEY('StadtId') REFERENCES 'Städte'('Id'), FOREIGN KEY('PräsidentId') REFERENCES 'Präsidenten'('Id') ,CONSTRAINT exclusive_präsidentschaft UNIQUE ('PräsidentId'));")
database.execute_query("CREATE TABLE 'Spieler' ('Id' INTEGER PRIMARY KEY, 'Name' Varchar NOT NULL, 'Alter' INTEGER NOT NULL, 'Position' Varchar NOT NULL, 'VereinId' INTEGER NOT NULL, FOREIGN KEY('VereinId') REFERENCES 'Vereine'('Id'));")
DatabaseSeeder.py: this class uses the Database class within its static methods and tries to insert
the 20 cities into the database.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Database import Database
class DatabaseSeeder:
database = 0
#staticmethod
def seed(database):
DatabaseSeeder.seed_cities(database)
DatabaseSeeder.seed_presidents(database)
DatabaseSeeder.seed_clubs(database)
DatabaseSeeder.seed_players(database)
#staticmethod
def seed_cities(database):
print("#DatabaseSeeder - seed cities")
cities = [
"Berlin",
"Hamburg",
"München",
"Köln",
"Frankfurt am Main",
"Stuttgart",
"Düsseldorf",
"Dortmund",
"Essen",
"Leipzig",
"Bremen",
"Dresden",
"Hannover",
"Nürnberg",
"Duisburg",
"Bochum",
"Wuppertal",
"Bielefeld",
"Bonn",
"Münster"
]
insert_city_sql_template = "INSERT INTO 'Städte' ('{0}') VALUES ('{1}');"
for city in cities:
sql_query = insert_city_sql_template.format("Name", city)
print(sql_query)
database.execute_query(sql_query)
My template for createing the final sql statement looks like this
insert_city_sql_template = "INSERT INTO 'Städte' ('{0}') VALUES ('{1}');"
It gets formatted into the final sql statement here
sql_query = insert_city_sql_template.format("Name", city)
When I print the sql statement before it is executed it looks like this
INSERT INTO 'Städte' ('Name') VALUES ('Berlin');
Application.py: in my main class I create a new database connection at first and hand this connection over to the DatabaseSeeder class.
from tkinter import *
import sqlite3
from sqlite3 import Error
from Database import Database
from table import Table
from DatabaseCreator import DatabaseCreator
from DatabaseSeeder import DatabaseSeeder
def main():
database_path = "./database.db"
DatabaseCreator.create(database_path)
database = Database(database_path)
DatabaseSeeder.seed(database)
When I execute my code I don't get any error message
but the entries just won't show up in the database.
When I copy the SQL statement from my code and directly execute it on the sqlite cli it works perfectly fine.
I hope someone of you knows what I am missing. Thanks a lot :)

Okay I found a solution thanks to #stovfl. I really was missing the commit statement. Now my execute_query method looks like this with a commit at the end.
def execute_query(self, query):
try:
database_cursor = self.database_connection.cursor()
database_cursor.execute(query)
except sqlite3.IntegrityError as e:
print('sqlite error: ', e.args[0]) # column name is not unique
self.database_connection.commit()
Thanks a lot for your help and always remember to commit your changes :D
Greetings

Related

Can't insert into table if table already exists

So I'm trying to insert a class variable into a mysql database and I'm having problems.
mysql.connector.errors.ProgrammingError: 1050 (42S01): Table 'ordertable' already exists
This message pops up when i try to insert values into a table even when i know the table exists.
order.py
import tkinter
from tkinter import *
import connection
import mysql.connector
class MenuWindow():
def init(self):
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
mycursor =db.cursor()
orderData = [(None, self.varTotal.get())]
for element in orderData:
mycursor.execute("INSERT INTO ordertable (orderid,total) VALUES (?,?)", element)
db.commit()
The table is created in this file
connection.py
def get_connection():
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
mycursor = db.cursor()
mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")
The error message does not complain about the insert. It complains about the create, because connection.py attempts to create the table when it already exists.
You only need to create the table exactly once, you do not need to create it whenever you reconnect.
Remove the line of
mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")

Insert Variables With Python And Tkinter, Into Sqlite3 Table

Sorry this is my first post.
I try to insert into sqlite3 table datas that i get using tkinter entries (python)
but i always obtain empty fields in the table.my code:
import sqlite3
from tkinter import *
def data_entry():
CDB.execute('insert into COSTUMERS (NAME,CODE)values(?,?)', (NAME_E,CODE_E))
DB.commit()
CDB.close()
DB.close()
X=Tk()
NAME=StringVar()
CODE=StringVar()
DB=sqlite3.connect('DB.db')
CDB=DB.cursor()
CDB.execute('''create table if not exists COSTUMERS
(ID integer primary key autoincrement,
NAME text(20), CODE text(10))''')
NAME_E=Entry(X,textvariable=NAME).pack()
CODE_E=Entry(X,textvariable=CODE).pack()
SAVE=Button(X,text='SAVE',command=data_entry).pack()
X.mainloop()
I think you should refactoring your code.
First of all use a naming convention on sql commands, that is, the uppercase
commands and the rest in lowercase.
This also for what concerns the code, see pep 8
I modified your script, in sqlite you don’t need to declare an autoincrement field
if you declare it as primary key.
I did not close the cursor and the database to insert more records as you can see
from the attached images.
And you don’t even need to declare Entry if you use textvariable, you can use
these directly to pass the values.
#!/usr/bin/python3
import tkinter as tk
import sqlite3 as lite
def data_entry():
sql = "INSERT INTO customers (customer,code)VALUES(?,?)"
args = (customer.get(),code.get())
print(sql, args)
cur.execute(sql, args)
dbms.commit()
sql = "SELECT * FROM customers"
cur.execute(sql)
rs = cur.fetchall()
for i in rs:
print(i)
#cur.close()
#dbms.close()
tk.X=tk.Tk()
customer = tk.StringVar()
code = tk.StringVar()
dbms = lite.connect('DB.db')
cur = dbms.cursor()
sql = "CREATE TABLE IF NOT EXISTS customers (customer_id INTEGER PRIMARY KEY, customer TEXT, code TEXT);"
cur.execute(sql)
tk.Entry(tk.X,textvariable=customer).pack()
tk.Entry(tk.X,textvariable=code).pack()
tk.Button(tk.X, text="Save", command=data_entry).pack()
tk.X.mainloop()

Storing information in a file, Python

I'm making a car rental console base program in Python where I need to save data about cars I store (such as brand, registration number etc).
What would be the ideal type of file for such a thing, and how to iniciate it?
You can use sqlite3 to store the information.
You can create a table with columns such as brand,registration number etc.
If the registration number is unique to single type of car you can also take care of that condition in sqlite3
syntax is as simple as:
For creating table:
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY
(REGISTRATION_NO INT PRIMARY KEY NOT NULL,
BRAND TEXT NOT NULL
);''')
print "Table created successfully";
conn.close()
For insertion:
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("INSERT INTO COMPANY (REGISTRATION_NO,BRAND) \
VALUES (1, 'PAGANI')");
conn.commit()
conn.close()
For more information:
https://docs.python.org/2/library/sqlite3.html

SQLite-Manager on Firefox and Python

I have written a small test application using SQLite with Python 3.3:
import sqlite3
MDB = sqlite3.connect('D:\MDB.db') # create the db object
cursor = MDB.cursor() # assign a cursor
cursor.execute('''CREATE TABLE IF NOT EXISTS section (
Code INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Description TEXT )
''')
cursor.execute('''DELETE FROM section''') # delete contents for reruns
cursor.execute('''INSERT INTO section
(Description)
VALUES (?)
''', ('Abdul, Paula',))
cursor.execute('''INSERT INTO section
(Description)
VALUES (?)
''', ('ABWH',))
print('Results:\n')
cursor.execute('''SELECT * FROM section''')
selection = cursor.fetchall()
for row in selection:
print('\t', row)
The SELECT statement shows the results expected (seeming to indicate that the row exists), but if I connect to the database with SQLite-Manager, the table exists but is empty, and if I try the same query with another script connected to the database, nothing is returned. Can anyone please explain what I am doing wrong?
You're not saving changes (calling MDB.commit).

How to deal with configuration variables in Python?

I'm new to Python and I'm doing some tests with it.
What I need to know is what is the best way of dealing with configuration variables.
For example, for this code:
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python
class TwitterC:
def logtodatabase(self, tweet, timestamp):
# Will log to the database
database = sqlite3.connect('database.db') # Create a database file
cursor = database.cursor() # Create a cursor
cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
# Assign the values for the insert into
msg_ins = tweet
timestamp_ins = timestamp
values = [msg_ins, timestamp_ins]
# Insert data into the table
cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
database.commit() # Save our changes
database.close() # Close the connection to the database
In this code, how can I replace 'database.db' with a variable outside of the class, for a better configuration. ?
Best Regards,
Or you could use argparse if you want to pass in configuration from the command line.
Then when creating the TwitterC class, you could pass in the configuration options you want.
class TwitterC:
def __init__(self, database):
self.database = database
def logtodatabase(self, tweet, timestamp):
# Will log to the database
database = sqlite3.connect(self.database) # Create a database file
#(...)
You could use ConfigParser out of the Python Standard Library.
You can create a python script that include the configuration variables:
config.py:
dbname = 'database.db'
...
your file:
import config
database = sqlite3.connect(config.dbname)

Categories

Resources