python gets MySQL database information

There are five steps as follows
  • 1 Connect to the database
import pymysql


# 这里的connect,也可以写为Connection和Connect
database = pymysql.connect(
    host='localhost', # 如果是服务器,则输公网ip
    user='root', # 当时设置的数据超级管理员账户
    passwd='xxxxxx', # 当时设置的管理员密码
    port=3306, #MySQL数据的端口为3306,注意:切记这里不要写引号''
    database='momo' # 当时在MySQL中创建的数据库名字
    )
  • 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() # 获取一条数据
  • 6 close the connection
database.close()
  • Execution result display
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:刘若英

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325682245&siteId=291194637