1. 安装PyMySQL

pip install PyMySQL

  1. 写python代码操作数据库 ```python import pymysql

打开数据库连接

db=pymysql.connect(host=’127.0.0.1’,user=’root’,password=’xxxx’,database=’xxxx’)

使用cusor()方法创建一个游标对象

cursor=db.coursor()

使用excute()方法执行SQL查询

cursor.execute(‘select * from demo limit 1’)

使用fetchone()方法获取单条数据

data=cursor.fetchone() print(data)

关闭数据库

db.close()

  1. 或者
  2. ```python
  3. import pymysql
  4. # 打开数据库连接,with会自动关闭数据库连接
  5. with pymysql.connect(host='127.0.0.1',user='root',password='xxxx',database='xxxx') as db
  6. # 使用cusor()方法创建一个游标对象
  7. cursor=db.coursor()
  8. # 使用excute()方法执行SQL查询
  9. cursor.execute('select * from demo limit 1')
  10. # 使用fetchone()方法获取单条数据
  11. data=cursor.fetchone()
  12. # 使用fetchall()方法获取多条数据
  13. # data=cursor.fetchall()
  14. print(data)