pymysql

一、建立数据库链接  

import pymysql

# 连接数据库
db = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="123456",
database="students",
charset="utf8"
)

 

二、创建游标对象

cur = db.cursor()

 

三、游标方法 :

  1)增、删、改、插入   

try:
  # 增、删、改、插入sql语句

  name ="zangsan"
  sql = "update student set score=100 where sname=%s"
  cur.execute(sql, [name, ])

  db.commit() #提交到数据库
except Exception as e:
  print(e)
  db.rollback() #回滚操作

2)查询

try:
  # 查询sql语句
  sql = "select * from student"
  cur.execute(sql)
  # 获取一个结果
  print(cur.fetchone())
  print(‘---------------------‘)

 

  print(cur.fetchmany(2)) # 获取多个查询结果
  print(‘---------------------‘)
  print(cur.fetchall()) # 查询所有结果

except Exception as e:
  print(e)

四、关闭游标对象

    cur.close()

五、断开数据库链接

    db.close()

pymysql

上一篇:springboot整合JDBC出现Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.


下一篇:MYSQL索引:索引的类型