Operational Error in SQL - python

I'm running sqlite3 and I cannot, for the life of me work out what is going wrong in my code. Baring in mind that it doesn't crash when creating other tables that come before it in the database. Part of me suspects it may be a case of capitalisation somewhere on an SQL statement but it was working normally a few days ago.
Create Table function
def create_table(db_name,table_name,sql):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",(table_name,))
result = cursor.fetchall()
keep_table = True
if len(result) == 1:
response = input("The table {0} already exists, do you wish to recreate (y/n): ".format(table_name)) #option to recreate the database
if response == 'y':
keep_table = False
print("The {0} table will be recreated - all existing data will be lost".format(table_name))
cursor.execute("drop table if exists {0}".format(table_name))
db.commit()
elif response == 'n':
print("The existing table was kept")
else:
print("Incorrect input, please try again.") #validation measure
if len(result) == 1:
response = input("The table {0} already exists, do you wish to recreate (y/n): ".format(table_name))
if response == 'y':
keep_table = False
print("The {0} table will be recreated - all existing data will be lost".format(table_name))
cursor.execute("drop table if exists {0}".format(table_name))
db.commit()
else:
keep_table = False
if not keep_table:
cursor.execute(sql)
db.commit()
Tables that are causing the problem?
def create_customer_table():
sql = """create table Customer
(CustomerID integer,
FirstName text,
LastName text,
Street text,
Town text,
Postcode text,
TelephoneNumber text,
EmailAddress text
primary key(CustomerID))"""
create_table(db_name, "Customer", sql)
*ignore the fact it isn't indented, it is on my program.
def create_customer_order_table():
sql = """create table CustomerOrder
(OrderID integer,
CustomerID integer,
Date date,
Time integer
primary key(OrderID)
foreign key(CustomerID) references Customer(CustomerID))"""
create_table(db_name, "CustomerOrder", sql)
Here is the error I receive:
Traceback (most recent call last):
File "/Users/X/Downloads/manage_table_March_2015.py", line 110, in <module>
create_customer_table()
File "/Users/X/Downloads/manage_table_March_2015.py", line 78, in create_customer_table
create_table(db_name, "Customer", sql)
File "/Users/X/Downloads/manage_table_March_2015.py", line 33, in create_table
cursor.execute(sql)
ysqlite3.OperationalError: near "(": syntax error

Related

same thread error or sqlite3.OperationalError: no such column: None

I want to add a new value into the field stock_type where user_id = 1
How i created the database in login.py:
import sqlite3
conn = sqlite3.connect("users.db")
cur = conn.cursor()
try:
cur.execute("""
CREATE TABLE users(
"user_id" integer,
"username" text,
"password" text,
"home" text,
"work" text,
"trans_meth" text,
"stock_type" text,
"inter_loc" text,
"reminders_str" text,
"news_prov" text,
"time_to_work" integer,
"stocks" integer,
"time" integer,
"reminders" integer,
"weather" integer,
"news" integer
)""")
cur.execute("""
INSERT INTO users(user_id)
VALUES(1)""")
conn.commit()
conn.close()
except:
print("table already exists")
code in register.py causing the issue:
import sqlite3
conn = sqlite3.connect("users.db")
cur = conn.cursor()
def update(stock, enter):
if enter > 0:
cur.execute(f"""
UPDATE users
SET stock_type = {stock}
WHERE user_id = 1;
""")
conn.commit()
conn.close()
return ""
at first i got an error
cur.execute(f"""
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 139888482103936 and this is thread id 139888351504128.
to fix this i added check_same_thread to sqlite3.connect() and set it to False
conn = sqlite3.connect("users.db", check_same_thread=False)
this fixed this issue however now
I got a new error
File "/workspaces/programming project/pages/register.py", line 93, in update
cur.execute(f"""
sqlite3.OperationalError: no such column: None
i have tried adding conn.commit() and conn.close() however neither of these have helped.
i have also tried adding:
conn = sqlite3.connect("users.db", check_same_thread=False) and
cur = conn.cursor()
into the update function however this also hasn't helped

sqlite3 | data doesn't save in table

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()

Using python in postgres and this error pops up

Getting this error:
Connection successful
Database Created Successfully
Connected to babynames database.
Traceback (most recent call last):
File "C:/Users/Joseph/Desktop/INFO153 Final/Info153PartII.py", line 44, in <module>
cur.execute('insert into boys values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))
TypeError: can only concatenate str (not "float") to str
import pandas as pd
df_boys = pd.read_csv('babynames.txt', delimiter=' ',header=None, usecols=(0,1,2,3) )
df_boys.columns = ["Rank", "Name", "Total Babies", "Total Percentage"]
df_girls = pd.read_csv('babynames.txt', delimiter=' ',header=None, usecols=(0,4,5,6) )
df_girls.columns = ["Rank", "Name", "Total Babies", "Total Percentage"]
#check the imported data
df_boys.head()
df_girls.head()
#psycopg2 library for connecting to PostgreSQL database
import psycopg2
conn = psycopg2.connect(database="postgres", user="postgres", password="postgres", host="127.0.0.1", port="5432")
conn.autocommit = True
print ("Connection successful")
#Create babynames database
cur = conn.cursor()
cur.execute('CREATE DATABASE babynames;')
print ("Database Created Successfully")
#connect to babynames database
conn_babynames = psycopg2.connect(database="babynames", user="postgres", password="postgres", host="127.0.0.1", port="5432")
conn_babynames.autocommit = True
print ("Connected to babynames database.")
cur = conn_babynames.cursor()
#create tables for boys and girls
cur.execute('CREATE TABLE Boys (Rank integer, Name varchar(25), Total_Babies float, Total_Percentage float);')
cur.execute('CREATE TABLE Girls (Rank integer, Name varchar(25), Total_Babies float, Total_Percentage float);')
#import data from dataframe to table using insert into statement
for i, row in df_boys.iterrows():
cur.execute('insert into boys values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))
for i, row in df_girls.iterrows():
cur.execute('insert into girls values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))
#execute sql queries and display result of analysis
cur.execute("select sum(total) as t_children from ( select sum(Total_Babies) as total from boys union select sum(Total_Babies) as total from girls) as t")
total_babies=cur.fetchone()
print("Total babies born that year = ",total_babies[0])
cur.execute("select total from ( select sum(Total_Babies) as total from boys union select sum(Total_Babies) as total from girls) as t")
babies=cur.fetchall()
if (babies[0]>babies[1]):
print("More boys were born in that year")
else:
print("More girls were born in that year")
cur.execute("select name from boys where Total_Babies> {}".format(total_babies[0]/2))
babies=cur.fetchall()
print(babies)
cur.execute("select name from girls where Total_Babies> {}".format(total_babies[0]/2))
babies=cur.fetchall()
print(babies)```
I believe the error is in "'"+row.tolist()[1]+"'" in your insert. As the error states, there's an issue trying to concatenate a float to a string. You should just be able to wrap the float in a str(), so all the concatenations (+) will be strings:
"'"+str(row.tolist()[1])+"'"
As some have pointed out, it is considered poor / dangerous practice to take strings from somewhere and concatenate them into your SQL queries. Malicious strings can wreck your database. My answer was for your question about why you got the error, but you would do well to look up parameterized SQL and how to implement using it with psycopg2

How to initialize a database just once on Python using SQLite 3?

I'm trying to make a python app where the user can add a row to a table and visualize all the rows. My problem is that it seems that every time I run the program, the database is created again, with no values. I say this because there is an autoincrement value that is always the same. When I write the program again on the cmd and insert the values by hand it does show me more than one value.
Here's the code:
import sqlite3
conn = sqlite3.connect("amigo_local_db.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)")
action = int(input("Insert an action: (1: Add row | 2: Close)"))
if(action == 1):
url = input("URL: ")
bash = input("BASH: ")
values = (url,bash)
c.execute("INSERT INTO images VALUES(null,?,?)",values)
else:
conn.close()
quit()
for row in c.execute("SELECT * FROM images"):
print(row)
conn.close()
You need to commit the INSERT transaction before closing, or it will not be persisted:
import sqlite3
conn = sqlite3.connect("amigo_local_db.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)")
action = int(input("Insert an action: (1: Add row | 2: Close)"))
if(action == 1):
url = input("URL: ")
bash = input("BASH: ")
values = (url,bash)
c.execute("INSERT INTO images VALUES(null,?,?)",values)
conn.commit()
else:
conn.close()
quit()
for row in c.execute("SELECT * FROM images"):
print(row)
conn.close()

How to store results from SQL query and use it?

I am trying to see whether the type is either a the letter "T" or between number 1-6 for the specific data entry found with name and password.
sql = 'SELECT type FROM table name WHERE name = "{}" AND password = "{}"'.format(username, password)
and then in psedocode i need something like:
if type =< 5:
int()
elif type = "T"
string()
I am using python 2.7
Here is a full script that will query the mysql DB, and use your above-mentioned logic to print the values. I've included the python code as well as the sample database code for this test case. Let me know if you have any questions.
Python
import pymysql
connection = pymysql.connect(user='username', passwd='password',
host='localhost',
database='database')
cursor = connection.cursor()
NAME = 'Person_A'
PASSWORD = 'Password_A'
query = ("SELECT * FROM My_TABLE WHERE NAME = '%(1)s' AND PASSWORD = '%(2)s';" % {"1" : NAME, "2" : PASSWORD})
cursor.execute(query)
for item in cursor:
type = item[0]
if type.isdigit():
if int(type) <6:
print('Type is a number less than 6')
else:
print('Type is a number but not less than 6')
else:
if type == 'T':
print('Type is a string == T')
else:
print('Type is a string but not the letter T')
MYSQL
CREATE TABLE MY_TABLE (TYPE VARCHAR(255), NAME VARCHAR(255), PASSWORD VARCHAR(255));
INSERT INTO MY_TABLE VALUES ('T','Person_A','Password_A'),('4','Person_A','Password_A'),('7','Person_B','Password_B'),('t','Person_C','Password_C');

Categories