简体   繁体   English

Python数据库插入MySQL

[英]Python database insert MySQL

I am trying to create a table in Python with MySQL, and then insert new values into the table! 我正在尝试使用MySQL在Python中创建一个表,然后将新值插入该表中!

The program works with no error message, but the table stays empty all the time. 该程序没有错误消息,但表始终保持为空。 Here are my python scripts: 这是我的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()

But any time I try to select data from this table, I get an empty set. 但是,每当我尝试从该表中选择数据时,都会得到一个空集。

I also tried without using format option, but still I get an empty set: 我也尝试过不使用format选项,但是仍然得到一个空集:

cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', (tw_userid, tw_state, tw_city, tw_text))

Any idea why the insert command doesn;t change the table at all? 知道为什么insert命令不更改表吗?

You need to use a comma to separate parameters in python. 您需要使用逗号分隔python中的参数。

cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})'.format(tw_userid, tw_state, tw_city, tw_text))

Should be: 应该:

data = (tw_userid, tw_state, tw_city, tw_text)
cursor.execute('INSERT INTO twitter VALUES ({0},{1},{2},{3})', data)

You can see the documentation for the python connector on the mysql documentation page . 您可以在mysql文档页面上查看python连接器的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM