There are five steps as follows
- 1 Connect to the database
import pymysql
database = pymysql.connect(
host='localhost',
user='root',
passwd='xxxxxx',
port=3306,
database='momo'
)
- 2 Get a cursor - that is, open up a buffer to store the result of the execution of the sql statement
cursor = database.cursor()
- 3 Execute sql statement, get/select data from sql, execute data
sql = 'select * from student'
cursor.execute(sql)
- 4 Get the execution result
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:刘若英