2025年3月27日 星期四 甲辰(龙)年 月廿六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python pymysql库操作mysql数据库

时间:01-18来源:作者:点击数:29

python pymysql库操作mysql数据库

  • # coding=utf-8
  • import pymysql
  • def gettime():
  • # 打开数据库连接
  • db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi',charset='utf8')
  • # 使用 cursor() 方法创建一个游标对象 cursor
  • cursor = db.cursor()
  • # 使用 execute() 方法执行 SQL 查询
  • cursor.execute("SELECT now()")
  • # 使用 fetchone() 方法获取单条数据.
  • data = cursor.fetchone()
  • print("当前时间: %s" % data)
  • # 关闭指针对象
  • cursor.close()
  • # 关闭数据库连接
  • db.close()
  • def insert():
  • # 打开数据库连接
  • db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
  • # 使用cursor()方法获取操作游标
  • cursor = db.cursor()
  • # SQL 插入语句
  • sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME)
  • VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
  • try:
  • # 执行sql语句
  • cursor.execute(sql)
  • # 提交到数据库执行
  • db.commit()
  • except:
  • # 如果发生错误则回滚
  • db.rollback()
  • # 关闭指针对象
  • cursor.close()
  • # 关闭数据库连接
  • db.close()
  • def query():
  • # 打开数据库连接
  • db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
  • # 使用cursor()方法获取操作游标
  • #cursor = db.cursor()
  • # 设置游标类型,默认游标类型为元组形式
  • # 将游标类型设置为字典形式
  • cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
  • # SQL 查询语句
  • sql = "SELECT * FROM EMPLOYEE"
  • try:
  • # 执行SQL语句
  • cursor.execute(sql)
  • # 获取所有记录列表
  • results = cursor.fetchall()
  • print(results)
  • # 游标类型为元组时的遍历方式
  • # data_dict = []
  • # for row in results:
  • # i = 0
  • # for field in cursor.description:
  • # record = {}
  • # rowname = field[0]
  • # rowvalue = row[i]
  • # record[rowname] = rowvalue
  • # data_dict.append(record)
  • # i += 1
  • # print(data_dict)
  • except:
  • print ("Error: unable to fetch data")
  • # 关闭指针对象
  • cursor.close()
  • # 关闭数据库连接
  • db.close()
  • def update():
  • # 打开数据库连接
  • db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
  • # 使用cursor()方法获取操作游标
  • cursor = db.cursor()
  • # SQL 更新语句
  • sql = "UPDATE EMPLOYEE SET AGE = AGE + 1"
  • try:
  • # 执行SQL语句
  • cursor.execute(sql)
  • # 提交到数据库执行
  • db.commit()
  • except:
  • # 发生错误时回滚
  • db.rollback()
  • # 关闭指针对象
  • cursor.close()
  • # 关闭数据库连接
  • db.close()
  • def delete():
  • # 打开数据库连接
  • db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
  • # 使用cursor()方法获取操作游标
  • cursor = db.cursor()
  • # SQL 删除语句
  • sql = "DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac1'"
  • try:
  • # 执行SQL语句
  • cursor.execute(sql)
  • # 提交修改
  • db.commit()
  • except:
  • # 发生错误时回滚
  • db.rollback()
  • # 关闭指针对象
  • cursor.close()
  • # 关闭连接
  • db.close()
  • if __name__ == "__main__":
  • gettime()
  • #insert()
  • #update()
  • #delete()
  • query()
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门