我不明白,我的代码有什么问题? 我创建了2个表''users'和'messages',但是当我尝试将数据插入到messages表中时,引发了这个奇怪的错误 -
sqlite3.OperationalError: table messages has no column named message
这是我的代码
conn = sqlite3.connect(self.path)
cur = conn.cursor()
# Create the table 'users'
cur.execute('''create table if not exists users
(uid INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT NOT NULL)''')
conn.commit()
# Create the table 'messages'
cur.execute('''create table if not exists messages (uid INTEGER NOT NULL, message TEXT)''')
conn.commit()
example_data1 = [(1,'Alex'), (2,'Jane'), (3,'Max'), (4,'Lui')]
example_data2 = [(1,'Hi!!!'), (1, 'Hello...'), (1, 'See you late!:)))'),
(2, 'Nice to meet you John'), (2, 'Bye-bye...'),
(3, 'Good morning')]
# Inserts example data to table -'users'
cur.executemany('''INSERT OR IGNORE INTO users(uid, name) VALUES(?,?)''', example_data1)
conn.commit()
cur.executemany('''INSERT INTO messages(uid, message) VALUES(?,?)''', example_data2)
conn.commit()
# Takes users name and count of messages of this users
cur.execute('SELECT users.name, count(messages.message) as count_msg FROM users LEFT JOIN messages ON users.uid = messages.uid GROUP BY users.name ORDER BY count_msg DESC')
result = cur.fetchall()
cur.close()
答案 0 :(得分:0)
您正在使用create table if not exists
,这将保留该表的任何旧版本。
要确保表具有所需的架构,请使用普通create table
。
可以使用drop table if exists
删除任何旧表。