I'm writing a program to store credit card values as practice.
I keep getting the error "sqlite3.OperationalError: no such column:
the table is created and the column: name.
the column name exists in in the cards table in cc.db in SQLiteStudio
any help appreciated.
import sqlite3
conn = sqlite3.connect('cc.db')
c = conn.cursor()
def createTABLE():
c.execute("""CREATE TABLE IF NOT EXISTS cards (
name text,
ccnumber integer,
exp_date text,
csv integer
)""")
conn.commit()
print('table created')
def entercard():
ccname = input('Enter the name of the new card: ')
ccnumber = input('Enter the card number: ')
ccexp_date = input('Enter the Expiration date: ')
cccsv = input('Enter the CSV number from the back of the card: ')
c.execute("INSERT INTO cards VALUES (?, ?, ?, ?),(name, ccnumber, exp_date, csv)");
conn.commit()
def printall():
for card in c.execute('SELECT * FROM cards'):
print(card)
createTABLE()
entercard()
printall()
conn.close()
I cannot determine why you're getting that particular error, but you have a problem with the following line:
c.execute("INSERT INTO cards VALUES (?, ?, ?, ?),(name, ccnumber, exp_date, csv)");
It is all a string. You need instead to separate the variables from the query string like so:
c.execute("INSERT INTO cards VALUES (?, ?, ?, ?)",(name, ccnumber, exp_date, csv))
I did the bellow in order to store values and retrieve them from the table.
You need to make the line look more like this.
c.execute("INSERT INTO cards(name,ccnumber,exp_date,csv) VALUES ('Tom','new1','new2','new3');")
Space
import sqlite3
conn = sqlite3.connect('cc.db')
c = conn.cursor()
def createTABLE():
c.execute("""CREATE TABLE IF NOT EXISTS cards (
name text,
ccnumber integer,
exp_date text,
csv integer)""")
conn.commit()
c.execute("INSERT INTO cards(name) VALUES ('Tom');")
conn.commit()
p=c.execute('SELECT * FROM cards')
j= p.fetchall()
print(j)
for i in j:
print(i)
print(p)
print('table created')
def entercard():
ccname = input('Enter the name of the new card: ')
c.execute("INSERT INTO cards(name) VALUES ('"+ccname+"')")
conn.commit()
def printall():
for card in c.execute('SELECT * FROM cards'):
print(card)
createTABLE()
entercard()
printall()
conn.close()
Related
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()
I am trying to program an sql database in python that asks for your name and stores it in a database. The problem is that it stores it but then when I reload, the data is gone. Here is the code:
import sqlite3
conn = sqlite3.connect('python.db')
c = conn.cursor()
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)')
name = input("What is your name?")
def data_entry():
number = "1234"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name))
conn.commit()
create_table()
data_entry()
c.close()
conn.close()
What could the problem be?
Thank you
Your problem was that you put con.commit() before you called your functions and actually wrote to the database. Here is a working example:
# Imports
import sqlite3
# Establish connection to database
conn = sqlite3.connect('python.db')
c = conn.cursor()
# Create global variable name
name = ""
def create_table():
global name # Retrieve global variable name
c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)') # DB execution
name = input("What is your name?") # Input to global variable name
def data_entry():
number = "1234"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name)) # Execute sql
# Call functions
create_table()
data_entry()
# Save changes to DB
conn.commit()
# Close connection
c.close()
conn.close()
Then you can see the entry you just created in this code:
c.execute('SELECT * FROM RecordONE')
print(c.fetchall())
Hope this was helpful :)
I am trying to get the user input the information so it can be stored in a database using SQLite3 but the error: "sqlite3.OperationalError: no such column: first_name" keeps popping up and I don't know why. Any suggestions?
import sqlite3
connection = sqlite3.connect('database.db')
cursor = connection.cursor()
create_table = '''
CREATE TABLE example (
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1));'''
cursor.execute(create_table)
first_name = input('First name : ')
surname = input('surname: ')
gend = input('Gender: ')
add_staff = '''INSERT INTO example (fname, lname, gender)
VALUES (first_name, surname, gend);'''
cursor.execute(add_staff)
cursor.execute('SELECT * FROM example')
result = cursor.fetchall()
for r in result:
print(r)
cursor.execute('SELECT * FROM example')
I would like to stick to sqlite3 rather than using another database library within python. Thanks.
You need to pass the values of your variables to your SQL command, using placeholders.
add_staff = '''INSERT INTO example (fname, lname, gender)
VALUES (?, ?, ?);'''
cursor.execute(add_staff, (first_name, surname, gend))
I try to use sqlite3 to import data to a table babyName in my AWS RDS database. For the two methods I tried, the first one data_entry() works fine every time but the second new_data_entry() gave me
Cursor is not connected
or
Not all parameters are used
error. Could you please help me?
import mysql.connector
from mysql.connector import errorcode
# start connection
try:
cnn = mysql.connector.connect(
user = '*****',
password = '*****',
host = '*****-mysql.*****.us-****-1.rds.amazonaws.com',
database = '*******')
print('It works!')
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
# start cursor
import sqlite3
c = cnn.cursor()
def creat_table():
c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
cnn.commit()
c.close()
cnn.close()
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
cnn.commit()
c.close()
cnn.close()
# creat_table()
data_entry()
print('It works!')
new_data_entry()
The error message I kept getting:
It works!
It works!
Traceback (most recent call last):
File "/Users/*****/sqlite3_python_cc.py", line 53, in <module>
new_data_entry()
File "/Users/*****/sqlite3_python_cc.py", line 45, in new_data_entry
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", values)
File "/Users/*****/anaconda/lib/python3.6/site-packages/mysql/connector/cursor.py", line 529, in execute
raise errors.ProgrammingError("Cursor is not connected")
mysql.connector.errors.ProgrammingError: Cursor is not connected
At the end of data_entry you have closed the connection to the database, cnn, which is saved as a variable in the global scope. When you attempt to run new_data_entry, the connection has already been closed, which is what is give you the error.
Instead, leave the connection open until you are finished.
import sqlite3
c = cnn.cursor()
def creat_table():
c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
cnn.commit()
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
cnn.commit()
def finish():
c.close()
cnn.close()
data_entry()
print('It works!')
new_data_entry()
finish()
I have the problem solved!
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (%s, %s, %s, %s)", (name, gender, frequency, year))
cnn.commit()
def finish():
c.close()
cnn.close()
Change all the "?" to "%s" and the codes all run through~ Thank you guys!
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.