【问题标题】:Why does SQLite (Python) say that the table "ORGANIZATION" already exists?为什么 SQLite (Python) 说“ORGANIZATION”表已经存在?
【发布时间】:2021-12-20 01:28:24
【问题描述】:

SQLite 表示“ORGANIZATION”表已经存在。

这是我的代码:

import sqlite3

con = sqlite3.connect('example4.db')
cur = con.cursor()

# Create table
cur.execute('''CREATE TABLE ORGANIZATION
               (ID int, NAME text, SURNAME text, NICKNAME text, ADDRESS chair(250), PHONE 
real, MAIL text, WEB text, INFO chair(250) )''')

# Insert a row of data
cur.execute("INSERT INTO ORGANIZATION VALUES (1, 'John', 'Stockton', 'JS', 'Nip and Tack 15', 
00000000000, 'info@info.xx',' https://www.info.xx', '-' )")

# Save (commit) the changes
con.commit()
con.close()

con = sqlite3.connect('example4.db')
cur = con.cursor()

for row in cur.execute('SELECT * FROM ORGANIZATION ORDER BY ID'):
    print(row)

我的预期结果是打印带有表格数据的行:

1, 'John', 'Stockton', 'JS', 'Nip and Tack 15', 00000000000, 'info@info.xx',' https://www.info.xx', '-'

【问题讨论】:

  • 您可能已经多次运行该程序,因此之前执行的表仍然存在于example4.db
  • 使用:CREATE TABLE IF NOT EXISTS ORGANIZATION ...

标签: python sql sqlite


【解决方案1】:

每次运行代码时,都会执行 CREATE TABLE ... 语句并尝试创建表。
如果表已经存在,你会得到错误:

...表“ORGANIZATION”已经存在...

您可以在声明中使用IF NOT EXISTS

sql = """
CREATE TABLE IF NOT EXISTS ORGANIZATION(
ID int, NAME text, SURNAME text, NICKNAME text, ADDRESS text, 
PHONE real, MAIL text, WEB text, INFO text)
"""
cur.execute(sql)

另外,没有数据类型chair(我怀疑你的意思是char,它也不是SQLite's data types之一),所以我改为TEXT

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2022-11-22
    • 2013-01-11
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多