"""
数据库的步骤:
1, 建立连接  ---> 认识小姐姐(加个微信)
2, 得到一个游标的对象(数据库的操作都是通过游标), 你和小姐姐约会,见面的机会。
3, execute(sql)  ,具体的而执行,(看电影)
4, 获取执行 sql 语句的结果。  (反馈和结果)
5, 关闭游标对象 (再见)
6, 关闭链接。 (微信晚安)
"""
import pymysql

# 建立连接
host = ''
port = 3306
username = ''
password = ''
db_name = ''

# 1,得到连接对象
connection = pymysql.connect(host=host,
                             port=port,
                             user=username,
                             password=password,
                             database=db_name)

# 2, 获取游标对象, 就相当于读取数据库内容的时候光标
cursor = connection.cursor()
print(cursor)

# 3, 执行 sql
sql = 'select id, reg_name from member limit 5;'
cursor.execute(sql)

# 4, 获取结果 fetchone(), sql 语句查询的一条结果
# 存储到元组中
rows = cursor.fetchone()
print(rows)

# 4, 获取结果 fetchall(), sql 语句查询的多条结果
# 存储到元组中

# cursor2 = connection.cursor()
# sql = 'select id, reg_name from member limit 5;'
# cursor2.execute(sql)
# rows = cursor2.fetchall()
# print(rows)
# 尽量避免使用一个游标进行多次操作。

# 关闭游标
cursor.close()
# 关闭链接
connection.close()

 

posted on 2021-10-27 11:10  熊猫星人  阅读(77)  评论(0编辑  收藏  举报