PyMySQL连接MySQL数据库

首先,

添加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()
# 断开数据库连接
posted @ 2018-02-27 20:18  此生不换Yang  阅读(445)  评论(0编辑  收藏  举报