首先,

添加PyMySQL模块:

 

 

代码:

import pymysql

db = pymysql.connect(host="localhost",
user="root",
password="123456",
db="world",
port=3306,
charset="utf8")
# 打开数据库连接

cur = db.cursor()
# 使用cursor()方法获取操作游标

sql = "SELECT `ID`, `Name`, `CountryCode`, `District`, `Population` FROM city LIMIT 1;"
# sql语句

try:
cur.execute(sql)
# 执行sql语句
results = cur.fetchall()
# 获取查询的结果

for row in results:
# 遍历结果
ID = row[0]
Name = row[1]
CountryCode = row[2]
District = row[3]
Population = row[4]
print(ID, Name, CountryCode, District, Population)
except Exception as e:
raise e
finally:
db.commit()
# 提交
cur.close()
# 关闭游标
db.close()
# 断开数据库连接
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!