This question already has an answer here:
Unfindable SQLite Syntax Error
(1 answer)
Closed 9 months ago.
error: cursor.execute(
sqlite3.OperationalError: near "Order": syntax error
import sqlite3
conn = sqlite3.connect("Cookie.DB")
print("The Employee database is created!")
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS Customer(
customerID TXT PRIMARY KEY NOT NULL,
customerFirstName TEXT NOT NULL,
customerLastName TXT NOT NULL,
address TXT NOT NULL,
email TXT NOT NULL,
Phone TXT NOT NULL,
creditCardInfo TXT NOT NULL
)
CREATE TABLE IF NOT EXISTS Order(
orderID TXT PRIMARY KEY NOT NULL,
FOREIGN KEY (customerID)
REFERENCES Customer (customerID),
customerName TXT NOT NULL,
FOREIGN KEY (cartID)
REFERENCES ShoppingCart (cartID),
orderPrice float NOT NULL,
dateCreated date NOT NULL,
dateShipped date NOT NULL
)
CREATE TABLE IF NOT EXISTS Cookies(
CookieID TXT PRIMARY KEY NOT NULL,
cookieName TXT NOT NULL,
unitCost float NOT NULL,
soldOutOrNot bool NOT NULL
)
CREATE TABLE IF NOT EXISTS ShoppingCart(
CartID TXT PRIMARY KEY NOT NULL,
FOREIGN KEY (customerID)
REFERENCES Customer (customerID),
FOREIGN KEY (cookieID)
REFERENCES Cookies (cookieID),
quantity INT NOT NULL,
dateAdded date NOT NULL,
soldOutOrNot bool NOT NULL
)
"""
)
conn.commit()
print("The employee table is created!")
I see the syntax you are using is wrong as far as I am able to understand try running individual queries like
import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
# run for each table...
cursor.execute("""CREATE TABLE albums
(title text, artist text, release_date text,
publisher text, media_type text)""")
I'm currently tryign to learn how to use SQLite3 and am trying to seperate setting up the DB through functions. My second function is where I'm having the error : AttributeError: 'NoneType' object has no attribute 'cursor'. After looking at the SQLite3 doucmentation, I got the impression that it's best to seperate diffrent methods for the DB into diffrent functions.
import sqlite3
from sqlite3 import Error
def create_connection(CRM):
"""
This Function will check to see if the Database is already created, if not will be created.
:param CRM: Location of the Database
:return: None
"""
db = None
try:
db = sqlite3.connect(CRM)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if db:
db.close()
return db
def create_table(db):
cur = db.cursor()
G8Personnel = ''' CREATE TABLE [IF NOT EXISTS] G8Personnel(
DoD INTEGER NOT NULL PRIMARY KEY,
Rank varchar NOT NULL,
FirstName varchar NOT NULL,
LastName varchar NOT NULL,
Role varchar NOT NULL
)'''
cur.execute(G8Personnel)
Company = '''CREATE TABLE [IF NOT EXISTS] Company(
CompanyName varchar PRIMARY KEY,
)'''
cur.execute(Company)
Employee = '''CREATE TABLE [IF NOT EXISTS] Employee(
AutoID INTEGER PRIMARY KEY AUTOINCREMENT,
FirstName varchar NOT NULL,
LastName varchar NOT NULL,
Email varchar NOT NULL,
JobTitle varchar,
WebPage varchar,
Notes varchar,
Company varchar
FOREIGN KEY (Company) REFERENCES Company(CompanyName)
)'''
cur.execute(Employee)
Meeting = '''CREATE TABLE [IF NOT EXISTS] Meeting(
AutoID INTEGER PRIMARY KEY AUTOINCREMENT,
Date1 real NOT NULL,
DoD INTEGER NOT NULL,
Employee INTEGER NOT NULL,
MeetingNotes varchar NOT NULL
FOREIGN KEY (DoD) REFERENCES G8Personnel (DoD)
FOREIGN KEY (Employee) REFERENCES Employee (AutoID)
)'''
cur.execute(Meeting)
if __name__ == '__main__':
db = None
create_connection(r'C:\Users\c94re\Documents\Git-Repo\CRM\CRM.db')
create_table(db)
You are not capturing the return value of create_connection. Try to assign the return type to a variable and try again.
if __name__ == '__main__':
db = create_connection(r'C:\Users\c94re\Documents\Git-Repo\CRM\CRM.db')
create_table(db)
I think this should do it, if you have other problems, please edit your question.
#-*-coding:utf-8-*-
import pymysql
class get_Mysql(object):
def __init__(self,dbname,company,goods_name):
self.dbname = dbname
self.table_name = '{}_{}'.format(company,goods_name)
self.conn = pymysql.connect(
host = '127.0.0.1',
user = 'root',
password = '123456',
port = 3306,
db = self.dbname,
charset = 'utf8'
)
self.cursor = self.conn.cursor()
def create_table(self):
create_sql = ''' CREATE TABLE '{tbname}' (
{id} INT (15) PRIMARY KEY,
{price} VARCHAR (15) NOT NULL,
{is_jd} CHAR (30) NOT NULL DEFAULT NULL,
{shopname} VARCHAR (30) NOT NULL DEFAULT NULL,
{brand} VARCHAR (20) NOT NULL DEFAULT NULL,
{years} VARCHAR (10) NOT NULL DEFAULT NULL,
{months} VARCHAR (10) NOT NULL DEFAULT NULL,
{weight} VARCHAR (10) NOT NULL DEFAULT NULL,
{thick} VARCHAR (40) NOT NULL DEFAULT NULL,
{long} VARCHAR (40) NOT NULL DEFAULT NULL,
{cpu_brand} VARCHAR (30) NOT NULL DEFAULT NULL,
{cpu_num} VARCHAR (20) NOT NULL DEFAULT NULL,
{sim_num} VARCHAR (25) NOT NULL DEFAULT NULL,
{sim} VARCHAR (20) NOT NULL DEFAULT NULL,
{rom} VARCHAR (10) NOT NULL DEFAULT NULL,
{ram} VARCHAR (15) NOT NULL DEFAULT NULL,
{sizes} VARCHAR (20) NOT NULL DEFAULT NULL,
{front_c} VARCHAR (20) NOT NULL DEFAULT NULL,
{back_c} VARCHAR (20) NOT NULL DEFAULT NULL,
{battery} VARCHAR (45) NOT NULL DEFAULT NULL,
{total_com} INT (20) NOT NULL DEFAULT 0,
{good_com} INT (20) NOT NULL DEFAULT 0,
{mid_com} INT (20) NOT NULL DEFAULT 0,
{bad_com} INT (20) NOT NULL DEFAULT 0,
{good_lv} FLOAT (20),
{mid_lv} FLOAT (20),
{bad_lv} FLOAT (20)
)
'''
try:
self.cursor.execute(create_sql.format(tbname=self.table_name,id='id',price='price',is_jd='is_jd',shopname='shopname',brand='brand',
years='years',months='months',weight='weight',thick='thick',long='long',cpu_brand='cpu_brand',
cpu_num='cpu_num',sim_num='sim_num',sim='sim',rom='rom',ram='ram',sizes='sizes',
front_c='front_c',back_c='back_c',battery='battery',total_com='total_com',good_com='good_com',
mid_com='mid_com',bad_com='bad_com',good_lv='good_lv',mid_lv='mid_lv',bad_lv='bad_lv'))
except Exception as e:
self.conn.rollback()
print('Create table failure, cause:',e)
else:
self.conn.commit()
print('The table is successful and the name is{}'.format(self.table_name))
def insert(self,data):
insert_sql = '''INSERT INTO '{tbname}'(id,price,is_jd,shopname,brand,years,months,weight,thick,long,cpu_brand,cpu_num,sim_num,sim,
rom,ram,sizes,front_c,back_c,battery,total_com,good_com.mid_com,bad_com,good_lv,mid_lv,bad_lv)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
'''
try:
self.cursor.execute(insert_sql.format(self.table_name),data['id'],data['price'],data['is_jd'],data['shopname'],data['brand'],data['years'],data['months'],data['weight'],data['thick'],
data['long'],data['cpu_brand'],data['cpu_num'],data['sim_num'],data['sim'],data['rom'],data['ram'],data['sizes'],data['front_c'],
data['back_c'],data['battery'],data['total_com'],data['good_com'],data['mid_com'],data['bad_com'],data['good_lv'],data['mid_lv'],data['bad_lv'])
except Exception as e:
self.conn.rollback()
print("Insert data failure, cause:",e)
else:
self.conn.commit()
print('Insert a data successfully!')
def close_table(self):
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
data ={'id':13108530411,'price':'2900.00','is_jd':'self-operation','shopname':'Chili mobile phone flagship store',"brand":'Hot pepper','years':'2017','months':'June','weight':'164(Contain the battery)',"thick":"8.9(Note: subject to the product configuration and manufacturing process, the actual size of the body is different. Please refer to the physical object)",
'long':'145(Note: subject to the product configuration and manufacturing process, the actual size of the body is different. Please refer to the physical object)','cpu_brand':'Snapdragon','cpu_num':'Four nuclear','sim_num':'Double card double for single pass','sim':'Nano SIM','rom':'32GB','ram':'4GB',"sizes":'5.0 inches','front_c':'8 million pixels','back_c':'16 million pixels','battery':'4000mAh (Typical capacity)/3900mAh (Nominal capacity','total_com':1400,
'good_com':1300,'mid_com':60,'bad_com':40,'good_lv':0.925,'mid_lv':0.043,'bad_lv':0.032}
my = get_Mysql('e-commerce','JD','phone')
my.create_table()
my.insert(data)
my.close_table()
I don't use markdown very much, my code indent is not a problem, I pasted code to stackoverflow some indentation problems, please ignore.
I made a mistake when I created the data table using pymysql:
Create table failure, cause: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''JD_phone' (\n id INT (15) PRIMARY KEY,\n price VARCHAR (15) NOT NUL' at line 1")
Insert data failure, cause: 'tbname'
So is my SQL statement wrong, and how do I write the remaining decimal point in the SQL statement?
Oh, I've solved it, by testing every field test,I changed the long field to longs to successfully create the data table, which should be the reason for the built-in name conflict with mysql.
The table is successful and the name is JD_phone
I want to create a new mysqldb table for each unique user, but i'm getting errors:
1.'bytes' object has no attribute 'encode'
2.Can't convert 'bytes' object to str implicitly
3.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Text'(
id int(11) NOT NULL AUTO_INCREMENT,
UserName text NOT NULL' at line 1
c.execute("CREATE TABLE IF NOT EXISTS {table_name}".format(table_name=belekas), (belekas) + """(
`id` int(11) NOT NULL AUTO_INCREMENT,
`UserName` text NOT NULL,
`Data` date NOT NULL,
`Laikas` time NOT NULL,
`KeyStrokes` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
con.commit()
c.execute("INSERT INTO {table_name} VALUES (id, %s, Data, Laikas, %s)".format(table_name=belekas),
(belekas, vartotojas, tekstas))
con.commit()
I tried using:
c.execute("CREATE TABLE IF NOT EXISTS" + vartotojas + """(
and this:
c.execute("CREATE TABLE IF NOT EXISTS" + repr(vartotojas.decode('utf-8')) + """(
and this:
c.execute("CREATE TABLE IF NOT EXISTS {this_table}".format(this_table=vartotojas), (vartotojas.encode("utf-8")) + """(
Can someone suggest solution for this problem?
I'm trying to create a database with several tables connecting to each other using foreign keys using sqlite3, and I'm writing in python.
Here is my code:
db = sqlite3.connect("PHLC.db")
cur = db.cursor()
# ############################
# delete original table if exist
# drop from the end (foreign key issue)
cur.execute("drop table if exists measurement")
cur.execute("drop table if exists mouse")
cur.execute("drop table if exists drug")
cur.execute("drop table if exists batch")
cur.execute("drop table if exists phlc")
# ############################
# create table
# ############################
# 1. phlc
cur.execute(
"""
CREATE TABLE phlc (
phlc_id INTEGER NOT NULL PRIMARY KEY,
cancer VARCHAR(30) NOT NULL,
histology VARCHAR(60) NOT NULL
)
"""
)
# 2. batch
cur.execute(
"""
CREATE TABLE batch (
batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
phlc_id INTEGER NOT NULL,
FOREIGN KEY (phlc_id) REFERENCES phlc (phlc_id),
batch_number INTEGER NOT NULL
)
"""
)
# 3. drug
cur.execute(
"""
CREATE TABLE drug (
drug_id INTEGER PRIMARY KEY AUTOINCREMENT,
drug_name VARCHAR(30) NOT NULL,
batch_id INTEGER NOT NULL,
FOREIGN KEY (batch_id) REFERENCES batch (batch_id)
)
"""
)
# 4. mouse
cur.execute(
"""
CREATE TABLE mouse (
mouse_id INTEGER PRIMARY KEY AUTOINCREMENT,
drug_id INTEGER NOT NULL,
FOREIGN KEY (drug_id) REFERENCES drug (drug_id)
)
"""
)
# 5. measurement
cur.execute(
"""
CREATE TABLE measurement (
measurement_index INTEGER PRIMARY KEY AUTOINCREMENT,
mouse_id INTEGER NOT NULL,
FOREIGN KEY (mouse_id) REFERENCES mouse (mouse_id),
day INTEGER NOT NULL,
tumor_volume FLOAT NOT NULL,
comment VARCHAR(255) NULL
)
"""
)
db.commit()
db.close()
The error I'm getting is at the batch table:
sqlite3.OperationalError: near "batch_number": syntax error
Can someone point out the problem with the code? (It worked fine with MySQL..)
According to the documentation, any table constraints must come after all column definitions:
CREATE TABLE batch (
batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
phlc_id INTEGER NOT NULL,
batch_number INTEGER NOT NULL,
FOREIGN KEY (phlc_id) REFERENCES phlc (phlc_id)
)
Alternatively, make the foreign key declaration a column constraint:
CREATE TABLE batch (
batch_id INTEGER PRIMARY KEY AUTOINCREMENT,
phlc_id INTEGER NOT NULL REFERENCES phlc (phlc_id),
batch_number INTEGER NOT NULL
)