我正在尝试使用 MySQL 在 Python 中创建一个表,然后将新值插入到该表中!
程序运行时没有错误消息,但表始终为空。这是我的 python 脚本:
cursor = conn.cursor()
cursor.execute('DROP TABLE twitter')
cursor.execute("CREATE TABLE twitter (id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id CHAR, state CHAR(2), city CHAR, tweet CHAR, PRIMARY KEY (id))")
### after getting some data, then insert the data into the table:
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
cursor.close()
conn.commit()
conn.close()
但是每当我尝试从此表中选择数据时,我都会得到一个空集。
我也尝试过不使用格式选项,但仍然得到一个空集:
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', (tw_userid, tw_state, tw_city, tw_text))
知道为什么插入命令根本不改变表格吗?
最佳答案
Python中参数之间需要用逗号分隔。
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))
应该是:
data = (tw_userid, tw_state, tw_city, tw_text)
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', data)
您可以在 mysql documentation page 上查看 python 连接器的文档。 .
关于Python数据库插入MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23773547/