【发布时间】:2021-02-20 22:20:39
【问题描述】:
我已经在我的计算机上安装了 MySQL,并且我已经成功地在 MySQL 8.0 命令行客户端上运行了查询
现在我正在尝试一些 python 脚本,我相信我已经完成了必要模块的 pip 安装,当我运行下面的代码时没有返回错误
但是,当我运行代码时,MySQL 8.0 命令行客户端中的数据库没有更新
代码示例 1
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='root',
db='news',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO headline_titles (Title, Language, Translation, Url) VALUES ('Dummy Title 2','German', 'Dummy Translation 2', 'Dummy Url 2');"
cursor.execute(sql)
# connection is not autocommit by default. So you must commit to save
# your changes.
finally:
connection.close()
代码示例 2
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="news") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("INSERT INTO headline_titles (Title, Language, Translation, Url) VALUES ('Dummy Title 2','German', 'Dummy Translation 2', 'Dummy Url 2');")
db.close()
我不确定上述代码是否链接到我计算机上安装的 MySQL 软件及其默认路径,或者正在尝试保存到 python 文件的路径。
由于我想将 python 文件发送给某人,我希望此代码执行到保存在 python 文件路径中的数据库,例如在与 python 文件相同的文件夹中。
我尝试将文本文件保存为 MySQL 文件扩展名并运行上述文件,但它似乎没有更新。
任何想法我做错了什么?
【问题讨论】:
标签: mysql python-3.x mysql-python