我正在尝试使用 MySQL 连接器/Python 将一些数据插入到本地 MySQL 数据库中——这显然是在不中断 C 编译器的情况下将 MySQL 集成到 Python 3 中的唯一方法。
我尝试了包中的所有示例;那些执行者可以很好地输入数据。不幸的是,我尝试将任何内容写入我的表都失败了。
这是我的代码:
import mysql.connector
def main(config):
db = mysql.connector.Connect(**config)
cursor = db.cursor()
stmt_drop = "DROP TABLE IF EXISTS urls"
cursor.execute(stmt_drop)
stmt_create = """
CREATE TABLE urls (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
str VARCHAR(50) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) CHARACTER SET 'utf8'"""
cursor.execute(stmt_create)
cursor.execute ("""
INSERT INTO urls (str)
VALUES
('reptile'),
('amphibian'),
('fish'),
('mammal')
""")
print("Number of rows inserted: %d" % cursor.rowcount)
db.close()
if __name__ == '__main__':
import config
config = config.Config.dbinfo().copy()
main(config)
输出:
Number of rows inserted: 4
我严格按照示例中提供的内容来编写我的代码,但我终其一生都无法找出问题所在。我在这里做错了什么?
使用脚本获取表数据工作正常,所以我不担心配置文件。我是数据库的根用户,所以权限也不成问题。
最佳答案
在 db.close()
之前,您需要添加一个 db.commit()
来提交您的更改!
关于python - 带 Python 的 DB-API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648861/