![](/img/trans.png)
[英]How to check if an entry already exists inside a table (SQL using Python)
[英]“How to fix the error table already exists in sql in a python IDE using CREATE method?”
當我使用Pycharm
時,錯誤不斷彈出:
Traceback (most recent call last):
File "C:/Users/aaa/.PyCharmCE2019.2/config/scratches/sql_class.py", line 11, in <module>
cur.execute(customers_sql)
sqlite3.OperationalError: table customers already exists
我正在使用Pycharm
導入sqlite3
import sqlite3
con = sqlite3.connect('data_info.sqlite3')
# 'connect' is similar to 'open' in a text file
cur = con.cursor()
# instantiate a cursor obj
customers_sql = """
CREATE TABLE customers (
id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL)"""
cur.execute(customers_sql)
products_sql = """
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price real NOT NULL)"""
cur.execute(products_sql)
orders_sql = """
CREATE TABLE orders (
id integer PRIMARY KEY,
date text NOT NULL,
customer_id integer ,
FOREIGN KEY (customer_id) REFERENCES customers(id) )
"""
cur.execute(orders_sql)
lineitems_sql = """
CREATE TABLE lineitems (
id integer PRIMARY KEY,
quantity integer NOT NULL,
total real NOT NULL,
product_id integer,
order_id integer,
FOREIGN KEY (product_id) REFERENCES products (id),
FOREIGN KEY (order_id) REFERENCES order (id) )"""
cur.execute(lineitems_sql)
#1st method of inputting
products_sql = "INSERT INTO products (name, price) VALUES ('introduction
to combinatorics', 6.89)"
cur.execute(products_sql)
#2nd method
products_sql = "INSERT INTO produts (name, price) VALUES(?, ?)"
cur.execute(products_sql,
('introduction to combinatorics', 7.99))
cur.execute(products_sql,
('introduction to combinatorics', 8.44))
# SELECTING OR EXTRACTING FROM A TABLE WITH DATA
cur.execute("SELECT id, name, price FROM products WHERE id =1")
result = cur.fetchone()
# fetchone is for picking just one
print(result)
預期的輸出是打印出表格。
您正在嘗試創建一個已經存在的表,這在Sqlite中是不可能的。
為了解決這個問題,您可以在查詢中使用IF NOT EXISTS語句。
因此,您的代碼塊將是:
customers_sql = """
CREATE TABLE IF NOT EXISTS customers (
id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL)"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.