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()
Related
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
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
I'm working with python and using pymysql library and i want to write a query that insert an array in a line where a column has some special value.
For example insert 'hi' into a column where user_id is 22
for that query i write this code
from pymysql import *
chat_id = 22
user_first_name = "hi"
db = connect(host="localhost", port=3306, user="root", passwd="",
db='support',charset='utf8')
cursor = db.cursor()
cursor.execute("""INSERT INTO users user_firstname VALUE %s WHERE user_id is
%s""",(user_first_name, chat_id))
db.commit()
how should i write this query in correct form?
If I'm undertanding, correctly, rather than an INSERT INTO, it seems you need an UPDATE:
cursor.execute("""UPDATE users SET user_firstname='%s' WHERE user_id=%s""",(user_first_name, chat_id))
Francisco is right though. If you have a user_id already, then an UPDATE should be used to change the value of and existing record. The INSERT command, creates a new record.
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).
I have created table using this create command as:
CREATE TABLE test_table(id INT PRIMARY KEY,name
VARCHAR(50),price INT)
i want to insert into this table wherein values are stored already in variable
bookdb=# name = 'algorithms'
bookdb-# price = 500
bookdb-# INSERT INTO test_table VALUES(1,'name',price);
I get the following error:
ERROR: syntax error at or near "name"
LINE 1: name = 'algorithms'
Can anyone point out the mistake and propose solution for the above?
Thanks in advance
Edit:
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),price INT)")
cur.execute("INSERT INTO book_details VALUES(1,'name',price)")
conn.commit()
except:
print "unable to connect to db"
I have used the above code to insert values into table,variables name and price containing the values to be inserted into table are available in file_content python file and i have imported that file.The normal INSERT statement takes values manually but i want my code to take values which are stored in variables.
SQL does not support the concept of variables.
To use variables, you must use a programming language, such as Java, C, Xojo. One such language is PL/pgSQL, which you can think of as a superset of SQL. PL/PgSQL is often bundled as a part of Postgres installers, but not always.
I suggest you read some basic tutorials on SQL.
See this similar question: How do you use script variables in PostgreSQL?
don't have postgres installed here, but you can try this
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),price INT)")
cur.execute("INSERT INTO book_details VALUES(1, '%s', %s)" % (name, price))
conn.commit()
except:
print "unable to connect to db"
If you are using PSQL console:
\set name 'algo'
\set price 10
insert into test_table values (1,':name',:price)
\g