“如何使用 CREATE 方法修复 python IDE 中 sql 中已存在的错误表?”

muy*_*iwa 5 python sql python-3.x

当我使用时,错误不断弹出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
Run Code Online (Sandbox Code Playgroud)

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

预期的输出是打印出表格。

alx*_*ves 9

您正在尝试创建一个已经存在的表,这在 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)"""
Run Code Online (Sandbox Code Playgroud)