sqlite3 | data doesn't save in table - python

The code works when I run it but when I run it again the data from the previous run is not saved, but the table is still there. I have tried many methods of saving the file and it still doesn't save
import sqlite3
conn = sqlite3.connect('conntact.db')
cursor = conn.cursor()
check = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='contacts'");
if check == 0:
cursor.execute('''CREATE TABLE contacts
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
EMAIL TEXT NOT NULL,
PHONE TEXT NOT NULL);''');
def add_contacts():
name1 = input("Enter contact name: ")
email1 = input("Enter contact email: ")
phone1 = input("Enter contact phone number: ")
id_s = input("Enter id: ")
cursor.execute("INSERT INTO contacts (ID, NAME,EMAIL,PHONE) VALUES (?,?,?,?)", (id_s, name1, email1, phone1));
def read_all_contact():
cursor.execute("SELECT * FROM contacts");
records = cursor.fetchall()
print(f"Total rows are: {len(records)}")
for row in records:
print(f'ID: {row[0]}')
print(f'Name: {row[1]}')
print(f'Email: {row[2]}')
print(f'Phone: {row[3]}\n')
add_contacts()
read_all_contact()
conn.close()
Any help would a apreciated

Remove check = ... line, which is wrong anyway.
Remove if check == 0
Replace "CREATE TABLE contacts" with "CREATE TABLE IF NOT EXISTS contacts"
Execute conn.commit()

Related

sorry for that kind of question but i must ask . How to create a table in SQLITE to ask me what to call a table

E.g. After launching the program:
It is in interactive mode
We are asked what name we want to create the database with;
After creating the database, the program asks us under what name to create the table in the database;
In the next step, the program asks us how many columns the table should have;
Enter the names of the mentioned number of columns and their types interactively;
Finally, create a database and a table with the columns indicated in it;
import sqlite3
connection = sqlite3.connect(input("Enter the name for base: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
columns_name = []
columns_amount = int(input("Enter amount of coulms and name them: "))
for item in range(columns_amount):
item = input("input theme mane of column: ")
columns_name.append(item)
cursor.execute("DROP TABLE IF EXISTS "+table_name+"" )
cursor.execute("CREATE TABLE IF NOT EXISTS "+ table_name +" ("+columns_name[0]+" INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+columns_name[1]+" TEXT, "+columns_name[2]+" TEXT, "+columns_name[3]+" TEXT )")
connection.commit()
You can just create the sql string for table creation inside the loop like -
import sqlite3
connection = sqlite3.connect(input("Enter the name for database: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
sql_string = "CREATE TABLE IF NOT EXISTS {} (".format(table_name)
columns_amount = int(input("Enter amount of columns: "))
for i in range(columns_amount):
column = input("input the name of column {}: ".format(i + 1))
datatype = input("input the type of column: ")
# You may want to check here whether column name and data type is valid or not
sql_string += "{} {},".format(column, datatype)
# remove the last extra comma
sql_string = sql_string[:-1]
sql_string += ")"
print(sql_string)
cursor.execute("DROP TABLE IF EXISTS {}".format(table_name))
# Finally create the table
cursor.execute(sql_string)
connection.commit()
Your code will not work because during table creation you are assuming that there are 3 columns which may not be true. So accessing those indices of columns_name might throw exception.

How to let user input TABLE name in sqlite3, python3?

I need to prompt a user to create a student table, check if a table with such a name exists in the database, and if not create it.
import sqlite3
conn = sqlite3.connect('School')
print ("Database has been created")
def create_table():
TableName = input("Enter table name: ")
tb_create ="""CREATE TABLE , (TableName,) (ID INT PRIMARY KEY,title VARCHAR(10), forename VARCHAR(20),
surname VARCHAR(20))"""
tb_exists ="SELECT name FROM sqlite_master WHERE type='table' AND name= ?", (TableName,)
if not conn.execute(tb_exists).fetchone():
conn.execute(tb_create)
print ("Table created successfully")
else:
print ("Table Exists!")
I know its possible to inser user inputed value into a table, but how do I create a table with inputed name? What should go after CREATE TABLE? If I use , (TableName,) the code wont compile.
Also, once the new table has been added to database, how do I indicate its name in INSER INTO query?
def insert_data():
conn.execute("INSERT INTO TableName (ID,title,forename,surname)VALUES \
(234,'Mr','XXX','XXX'")
conn.commit()
The correct syntax for a CREATE TABLE statement is:
CREATE TABLE tablename(column1 datatype1, column2 datatype2, ....)
Since you want the user to provide the name of the table, you can do it with string interpolation, because you can't pass it with a ? placeholder in the sql query as aparameter:
tb_create = f"CREATE TABLE [{TableName}](ID INTEGER PRIMARY KEY, title TEXT, forename TEXT, surname TEXT)"
The table's name must be enclosed inside square brackets, just in case the user provided a name that is not valid (for example it starts with digit or contains spaces).
Also, if you want the column ID to be autoincrement, you must use INTEGER instead of INT for its data type.
Also, there is no VARCHAR data type in SQLite. Use TEXT.
You can define the variable TableName as global so that you can use it in all the functions, like insert_data().
Use string interpolation for the INSERT statement also.
import sqlite3
conn = sqlite3.connect("School")
print ("Database has been created")
TableName = ""
def create_table():
global TableName
TableName = input("Enter table name: ").strip()
tb_exists ="SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?"
if not conn.execute(tb_exists, (TableName,)).fetchone():
tb_create = f"CREATE TABLE [{TableName}](ID INTEGER PRIMARY KEY, title TEXT, forename TEXT, surname TEXT)"
conn.execute(tb_create)
print("Table created successfully")
else:
print("Table Exists!")
def insert_data():
if len(TableName) > 0:
conn.execute(f"INSERT INTO [{TableName}] (ID,title,forename,surname) VALUES (234,'Mr','XXX','XXX')")
conn.commit()
create_table()
insert_data()
The name of the table, or of the columns cannot be parameterized, so you must build the query string. It means that you should control that the entered name is sane because building query from strings is know to be a vector for SQL injection.
But most (if not all) SQL database allow to create a table if it does not already exists. The syntax is just:
CREATE TABLE table_name IF NOT EXISTS (
column_name type,
...)
So here, you could just do:
import re
...
def create_table():
TableName = input("Enter table name: ")
# control name:
if not re.match(r'\w*$', TableName):
raise IllegalValue("Invalid table name")
tb_create =f"""CREATE TABLE {TableName} IF NOT EXISTS (ID INT PRIMARY KEY,title VARCHAR(10),
forename VARCHAR(20), surname VARCHAR(20))"""
conn.execute(tb_create)

Python 3.6 & Inserting Values into MariaDB via variable

Code description - Running a program to add values to a maria db table. The program executes and prompts for the variables without error but the table shows no rows when I query it. Any idea where I am going wrong? Wanted to make it dynamic so I am using variables for the db and the table.
######## Output #########
[root#localhost student_program]# python db_setup.py
Connection successful!!
Database already exists: students
create_table
/usr/local/lib/python3.6/site-packages/pymysql/cursors.py:329: Warning: (1050, " Table 'students_info' already exists")
self._do_get_result()
use students;
Enter the first name :Frank
Enter the last name: Brady
Enter the email address: frank#noemail.com
Enter the address: 300 Main Street, Belfast
Enter the DOB in YYYY-MM-DD: 1980-02-02
Enter the english mark: 90
Enter the maths mark: 80
Enter the history mark: 70
Enter the science mark: 45
('INSERT into students_info (firstname, lastname,email,address,DOB,english,maths,history,science) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);', ('Frank', 'Brady', 'frank#noemail.com', '300 Main Street, Belfast', '1980-02-02', '90', '80', '70', '45'))
######### Program below #################
import os,pymysql
mariadb_root = '/var/lib/mysql/'
db_to_create = 'students'
conn = pymysql.connect(host='localhost', user='xxx', passwd='xxx', cursorclass=pymysql.cursors.DictCursor)
print('Connection successful!!')
# Check if db exists, if not create
def check_db_exists():
dbfile = os.path.join(mariadb_root, db_to_create)
if not os.path.exists(dbfile):
cur = conn.cursor()
command = "CREATE DATABASE %s;" % db_to_create
print(command)
cur.execute(command)
print("Database created %s:", db_to_create)
else:
print("Database already exists: %s" % db_to_create)
check_db_exists()
def create_database():
cur = conn.cursor()
command = "use %s; " %db_to_create
cur.execute(command)
create_table = ("""
CREATE TABLE IF NOT EXISTS students_info (
ID int NOT NULL AUTO_INCREMENT,
firstname varchar(255),
lastname varchar(255),
email varchar(255),
address varchar(255),
DOB DATE,
english varchar(255),
maths varchar(255),
history varchar(255),
science varchar(255),
PRIMARY KEY (ID));
""")
print("create_table")
cur.execute(create_table)
print(command)
create_database()
def add_student():
firstname = input("Enter the first name :")
lastname = input("Enter the last name: ")
email = input("Enter the email address: ")
address = input("Enter the address: ")
DOB = input("Enter the DOB in YYYY-MM-DD: ")
english = input("Enter the english mark: ")
maths = input("Enter the maths mark: ")
history = input("Enter the history mark: ")
science = input("Enter the science mark: ")
cur = conn.cursor()
command = "use %s; " %db_to_create
cur.execute(command)
cur.execute = ("""INSERT into students_info (firstname, lastname,email,address,DOB,english,maths,history,science) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);""",
(firstname,lastname,email,address, DOB,english,maths,history,science))
print(cur.execute)
cur.close()
conn.close()
add_student()

PRAGMA foreign key error (Python)

Going to paste in the entire file because I have absolutely no idea how to fix my issue;
import sqlite3
import time
import datetime
import sys
conn = sqlite3.connect('offerdatabase1.db')
c = conn.cursor()
c.execute('PRAGMA foreign_keys = ON')
############################# Creating the Database Tables #############################
# Creating the 'Odds' Table
def create_odds_table():
c.execute("""CREATE TABLE IF NOT EXISTS Odds(OddsID INTEGER PRIMARY KEY,
TeamSelection TEXT,
BackOdds INTEGER,
LayOdds INTEGER)
""")
c.execute('PRAGMA foreign_keys = ON')
# # # Creating the 'Value' Table # # #
def create_value_table():
c.execute("""CREATE TABLE IF NOT EXISTS Value(ValueID INTEGER PRIMARY KEY,
BackStake INTEGER,
LayStake INTEGER,
Liability INTEGER,
NetValue INTEGER)
""")
c.execute('PRAGMA foreign_keys = ON')
# Creating the 'User' Table
def create_user_table():
c.execute("""CREATE TABLE IF NOT EXISTS User(UserID INTEGER PRIMARY KEY,
FirstName TEXT,
LastName TEXT,
Email TEXT,
Date TEXT,
Time TEXT)
""")
c.execute('PRAGMA foreign_keys = ON')
# Creating the 'Offer' Table
def create_offer_table():
c.execute("""CREATE TABLE IF NOT EXISTS Offer(OfferID INTEGER PRIMARY KEY,
OfferType TEXT,
OfferDesc TEXT,
Bookmaker TEXT,
Exchange TEXT,
OddsID INTEGER,
ValueID INTEGER,
UserID INTEGER,
FOREIGN KEY(OddsID) REFERENCES Odds(OddsID),
FOREIGN KEY(ValueID) REFERENCES Value(ValueID),
FOREIGN KEY(UserID) REFERENCES User(UserID))""")
c.execute('PRAGMA foreign_keys = ON')
# Running the Subroutines, in order to create the database with tables previously stated.
if __name__ == "__main__":
db_name = ('offerdatabase1.db')
c.execute('PRAGMA foreign_keys = ON')
create_odds_table()
create_value_table()
create_user_table()
create_offer_table()
############################# Inserting Data into Tables #############################
def data_entry_odds():
print('==================== Odds and Team Selection ====================')
TeamSelection = input('Team you selected: ')
BackOdds = input('Back Bet Odds: ')
LayOdds = input('Lay Bet Odds: ')
c.execute("INSERT INTO Odds (TeamSelection, BackOdds, LayOdds) VALUES (?, ?, ?)",
(TeamSelection, BackOdds, LayOdds))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
def data_entry_value():
print('================ Stakes, Liability and Net Value ================')
BackStake = input('Stake on Back Bet: ')
LayStake = input('Stake on Lay Bet: ')
Liability = input('Liability (applies only with exchange): ')
NetValue = input('Net value : ')
c.execute("INSERT INTO Value (BackStake, LayStake, Liability, NetValue) VALUES (?, ?, ?, ?)",
(BackStake, LayStake, Liability, NetValue))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
def data_entry_user():
print('======================== User Information =======================')
FirstName = input('Firstname: ')
LastName = input('Surname: ')
Email = input('Email Address: ')
Date = time.strftime("%d/%m/%Y")
Time = time.strftime("%H:%M")
c.execute("INSERT INTO User (FirstName, LastName, Email, Date, Time) VALUES (?, ?, ?, ?, ?)",
(FirstName, LastName, Email, Date, Time))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
def data_entry_offer():
print('======================= Offer Information =======================')
OfferType = input('Type of Offer: ')
OfferDesc = input('Offer Description: ')
Bookmaker = input('Name of Bookmaker: ')
Exchange = input('Name of Exchange: ')
c.execute("INSERT INTO Offer (OfferType, OfferDesc, Bookmaker, Exchange) VALUES (?, ?, ?, ?)",
(OfferType, OfferDesc, Bookmaker, Exchange))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
########################### Text Based User Interface ###########################
def rootchoice():
userchoice = input('Would you like to track a bet? (Y - Yes, N - No) ')
if userchoice.upper() == 'Y':
yeschoice()
elif userchoice.upper() == 'N':
nochoice()
else:
print('*ERROR* - Please enter either \'Y\' or \'N\' (no other characters accepted)')
rootchoice()
def yeschoice():
data_entry_user()
data_entry_offer()
data_entry_odds()
data_entry_value()
print('Data entry complete, recorded successfully.')
loopchoice()
def nochoice():
print('Thank you for using James\' Betting Tracker, goodbye!')
sys.exit()
def loopchoice():
loopuserchoice = input('Would you like to track another bet? (Y - Yes, N - No) ')
if loopuserchoice.upper() == 'Y':
yeschoice()
elif loopuserchoice.upper() == 'N':
nochoice
else:
print('*ERROR* - Please enter either \'Y\' or \'N\' (no other characters accepted)')
loopchoice()
print('Welcome to James\' Betting Tracker!')
rootchoice()
Excuse the annotation and ridiculous headings, I am writing this code for a school project. After reading around the subject of foreign keys within sqlite3, I stumbled across the command;
PRAGMA foreign_keys = ON
After reading around about it, I was told that you had to set PRAGMA foreign_keys to ON everytime a database connection was made.
I've done this, but the foreign keys still don't work with my database.
Any help would be greatly appreciated, i'm incredibly new to the world of python and programming in general, thanks!
Foreign key constraints are called "constraints" because they are constraints, i.e., the constrain the values in the database. In other words, they prevent you from inserting values that would violate the rules.
In this case, you would get an error if you tried to insert an invalid OddsID, ValueID or UserID number (one that does not exist in the parent table) into the Offers table.
But you never do that; you leave those columns empty.
It is not possible for the database to automatically insert a reference to a row in the parent table – which of those rows should it choose?
If your data model requires that all Offers rows have valid references to the other three tables, add NOT NULL constraints to those columns.

Trying to search a column on SQLite Python so that it only returns the information searched

New to Python and Databases
I have a database table set up with a column of usernames. I want the user to be able to search through the table via a raw_input and only return the values which are associated with that user name.
E.g. user searches for Bill and it only displays Bill's records ordered by a specified column
This is what I have so far but its obviously VERY wrong, hope someone can help:
def find_me(db, column_name):
db = sqlite3.connect(db)
cursor = db.cursor()
name = raw_input("Please enter your username: ")
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
cursor.execute("SELECT * FROM username ORDER BY "+column_name+" ASC")
name = cursor.fetchone()
next = cursor.fetchone()
Thank you in advance
You want to make the query similar to the following:
cursor.execute("SELECT name FROM username WHERE name=?", (name,))
This uses query parameters, so it's correctly escaped for the data provided. Then just adapt this to SELECT * and whatever else you want from the result.
Try working with this:
name = raw_input("Please enter your username: ")
query = "SELECT * FROM username WHERE name=? ORDER BY {0}".format(column_name)
cursor.execute(query, (name,))
for row in cursor:
print row

Categories