I have a syntax problem using sqlite3 with Python around the last line of the below code:
playerName = input("Enter your name: ")
money = input("Enter credits: ")
conn = sqlite3.connect("highscore.db")
c = conn.cursor()
c.execute("CREATE TABLE players(name TEXT, money INTEGER)")
c.execute("INSERT INTO players VALUES('%s','%s')", playerName, money)
How can I resolve this ?
Change this line:
c.execute("INSERT INTO players VALUES('%s','%s')", playerName, money)
To:
c.execute("INSERT INTO players VALUES(?,?);",(playerName, money))
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'm making a program that connects to a SQL database for me to enter in data. Instead of entering data into the table manually, I wanted to make a program do it. So it's asks me a series of questions, then inputs the answers into the table. I am not sure how to do that. My issue is at the end with the cursor execute.
I am not sure how I can incorporate the input answers into that execute function. Would it be something like this? The .format is showing up as a string, so I am not sure how to implement this.
VALUES
('{}'.format(category), '{}'.format(description), '{}'.format(date), '{}'.format(price), '{}'.format(vehicle))
Here is the code below:
import time
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TJDESKTOPPC;'
'Database=carparts;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM carparts.dbo.modifications
''')
conn.commit()
# Menu starts below
database = "carparts"
print("Welcome to the program!")
print()
print("You are connected to {} database".format(database))
print()
print()
print("The current columns in the table are...")
print()
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TJDESKTOPPC;'
'Database=carparts;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM carparts.dbo.modifications where 1=2')
headers = [i[0] for i in cursor.description]
print(headers)
print()
print("Categories are: engine, suspension, exhaust, or transmission")
print()
category = str(input("Please enter category: "))
print()
description = str(input("Please enter the description of the part: "))
print()
purchase_date = input("Please enter the purchase date in (YYYY-MM-DD): ")
print()
price = int(input("Please enter the price amount: "))
print()
vehicle = str(input("What vehicle is this for? (Model): "))
print()
print("Thanks!")
time.sleep(3)
print("\n" * 5) # This will the clear screen of any previous code
print("Adding the category, description, purchase date, price, and vehicle to the table...")
time.sleep(2)
cursor.execute('''
INSERT INTO carparts.dbo.modifications (category, description, purchase_date, price,
vehicle)
VALUES
('exhaust', 'Flowmaster Cat-back Exhaust', '2015-12-08', '551', 'focus_st')
''')
conn.commit()
The snippet above for INSERT INTO actually works, but I need to put the values in manually how it is. So how do I get the variable input (category, description, date, etc) in that string?
Try this,
Here you need to provide your variable data you want to insert and also need to add {} in single quotes like this '{}'.
So that your after providing value in format "'{}'".format("category_input") is looks like 'category_input' and it doesn't effect if you have a number.
cursor.execute('''INSERT INTO carparts.dbo.modifications (category, description,
purchase_date, price, vehicle) VALUES ('{}', '{}', '{}', '{}', '{}')'''.format(category, description, purchase_date, price, vehicle))
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()
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()
I want to insert a row into my table, but I am getting an error. Where am I going wrong?
CREATE TABLE person (
name VARCHAR(40),
birthday DATE,
PRIMARY KEY (name)
);
Now in python I try to insert a person with the following statement...
curs = connection.cursor
name = input("Name: ")
birthday = input("Birthdate(yyyy-mm-dd): ")
insert = """insert into people(name, birthday) values (:name,:birthday)"""
curs.execute(insert,{'name':name,'to_date(birthday, "yyyy-mm-dd")':birthday})
I get the following error:
curs.execute(insert,{'name':name,'to_date(birthday, "yyyy-mm-dd")':birthday})
cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number
Figured it out, I was inserting the date wrong.
My syntax was incorrect and should have been:
curs = connection.cursor
name = input("Name: ")
birthday = input("Birthdate(yyyy-mm-dd): ")
insert = """insert into people(name, birthday) values (:name, to_date(:birthday, 'yyyy-mm-dd'))"""
curs.execute(insert,{'name':name, 'birthday':birthday})