分为五步,如下所示
import pymysql
database = pymysql.connect(
host='localhost',
user='root',
passwd='xxxxxx',
port=3306,
database='momo'
)
- 2 获取一个游标 — 也就是开辟一个缓冲区,用于存放sql语句执行的结果
cursor = database.cursor()
- 3 执行sql语句,从sql中获取/选择数据,执行数据
sql = 'select * from student'
cursor.execute(sql)
data = cursor.fetchall() # 获取所有的数据
for i in data:
print('id:%s name: %s' % (i[0], i[1]))
data = cursor,fetchone() # 获取一条数据
database.close()
id:1 name:章子怡
id:2 name:刘明湘
id:3 name:蔡佩轩
id:4 name:林志玲
id:5 name:白百合
id:6 name:杨钰莹
id:7 name:杨贵妃
id:8 name:夏雨荷
id:9 name:张柏芝
id:10 name:刘若英