enter code here
import sqlite3
conn = sqlite3.connect('tutorial.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE example(Language VARCHAR, Version REAL, Skill
TEXT)")
def enter_data():
c.execute("INSERT INTO example VALUES('Python', 2.7, 'Beginner')")
c.execute("INSERT INTO example VALUES('Python', 3.3, 'Intermediate')")
c.execute("INSERT INTO example VALUES('Python', 3.4, 'Expert')")
conn.commit()
def enter_dynamic_data():
lang = input("What language? ")
version = float(input("What version? "))
skill = input("What skill level? ")
c.execute("INSERT INTO example (Language, Version, Skill) VALUES (?, ?, ?)",
(lang, version, skill))
conn.commit()
enter_dynamic_data()
conn.close()
回溯(最近通话最近一次):
File "C:\Users\karti\Desktop\sqlite3\0304 - inserting dynamic data.py", line 25, in <module>
enter_dynamic_data()
File "C:\Users\karti\Desktop\sqlite3\0304 - inserting dynamic data.py", line 20, in enter_dynamic_data
c.execute("INSERT INTO example (Language, Version, Skill) VALUES (?, ?, ?)", (lang, version, skill))
sqlite3.OperationalError: no such table: example
如何消除此错误?
答案 0 :(得分:0)
该消息表明表示例不存在。您似乎没有在呼叫 create_table (或 enter_data )
尝试使用:-
import sqlite3
conn = sqlite3.connect('tutorial.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS example(Language VARCHAR, Version REAL, Skill TEXT)") #<<<<<<<<<< CHANGED
def enter_data():
c.execute("INSERT INTO example VALUES('Python', 2.7, 'Beginner')")
create_table() #<<<<<<<<<< ADDED
enter_data() #<<<<<<<<<< ADDED
c.execute("INSERT INTO example VALUES('Python', 3.3, 'Intermediate')")
c.execute("INSERT INTO example VALUES('Python', 3.4, 'Expert')")
conn.commit()
def enter_dynamic_data():
lang = input("What language? ")
version = float(input("What version? "))
skill = input("What skill level? ")
c.execute("INSERT INTO example (Language, Version, Skill) VALUES (?, ?, ?)",
(lang, version, skill))
conn.commit()
enter_dynamic_data()
cursor = c.connection.cursor() #<<<<<<<<<< ADDED
cursor.execute("SELECT * FROM example") #<<<<<<<<<< ADDED
for row in cursor: #<<<<<<<<<< ADDED
print("Language=", row[0], " Version=", row[1], " Skill=", row[2]) #<<<<<<<<<< ADDED
conn.close()
以上结果为:-
What language? Basic What version? 3 What skill level? Easy Language= Python Version= 2.7 Skill= Beginner Language= Python Version= 3.3 Skill= Intermediate Language= Python Version= 3.4 Skill= Expert Language= Basic Version= 3.0 Skill= Easy Process finished with exit code 0