zoukankan      html  css  js  c++  java
  • 雷林鹏分享:python mysql增删改查

      import pymysql

      ''''fetchone用法 (获取一条数据)'''

      def selectmysql():

      # 打开数据库连接

      db=pymysql.connect("localhost","root","root","kettle")

      #使用cursor()方法获取操作游标

      cursor=db.cursor()

      sql="select * from beijing"

      #使用excute方法执行sql语句

      cursor.execute(sql)

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

      data=cursor.fetchone()

      print(data)

      '''fetchall() 接收全部的返回结果行'''

      def selectfetchall():

      # 打开数据库连接

      db = pymysql.connect("localhost", "root", "root", "kettle")

      # 使用cursor()方法获取操作游标

      cursor = db.cursor()

      sql = "select * from beijing"

      try:

      # 使用excute方法执行sql语句

      cursor.execute(sql)

      #获取所有记录列表

      res=cursor.fetchall()

      for row in res:

      name=row[0]

      num=row[1]

      #打印结果

      print("name=%s,num=%s"%(name,num))

      except:

      print("error")

      #关闭数据库连接

      db.close()

      '''数据库插入操作'''

      def insert():

      # 打开数据库连接

      db = pymysql.connect("localhost", "root", "root", "kettle")

      # 使用cursor()方法获取操作游标

      cursor = db.cursor()

      sql = "insert into beijing(name,num) VALUES ('吴林祥','666')"

      try:

      # 使用excute方法执行sql语句

      cursor.execute(sql)

      db.commit()

      print("插入数据库成功!")

      except:

      db.rollback()

      db.close()

      '''数据库更新操作'''

      def update():

      # 打开数据库连接

      db = pymysql.connect("localhost", "root", "root", "kettle")

      # 使用cursor()方法获取操作游标

      cursor = db.cursor()

      sql = "update beijing set num=8 WHERE name='延庆区'"

      try:

      # 使用excute方法执行sql语句

      cursor.execute(sql)

      db.commit()

      print("更新数据库成功!")

      except:

      db.rollback()

      db.close()

      '''删除操作'''

      def delete():

      # 打开数据库连接

      db = pymysql.connect("localhost", "root", "root", "kettle")

      # 使用cursor()方法获取操作游标

      cursor = db.cursor()

      sql = "delete from beijing where name='吴林祥'"

      try:

      # 使用excute方法执行sql语句

      cursor.execute(sql)

      db.commit()

      print("删除数据成功!")

      except:

      db.rollback()

      db.close()

      if __name__ == '__main__':

      selectmysql()

      #insert()

      #selectfetchall()

      #update()

      #delete()(编辑:雷林鹏 来源:网络|侵删)

  • 相关阅读:
    [bzoj4417] [洛谷P3990] [Shoi2013] 超级跳马
    [bzoj4011] [洛谷P3244] [HNOI2015] 落忆枫音
    [bzoj1875] [洛谷P2151] [SDOI2009] HH去散步
    [bzoj4827] [洛谷P3723] [Hnoi2017] 礼物
    [bzoj2326] [洛谷P3216] [HNOI2011] 数学作业
    [bzoj3105] [cqoi2013] 新Nim游戏
    [YTU]_2353 ( 长方柱类【C++ 类定义】)
    [YTU]_2627 (职工工资统计)
    [YTU]_2769( 结构体--成绩统计)
    [YTU]_2577( 小数计算——结构体)
  • 原文地址:https://www.cnblogs.com/pengpeng1208/p/12567032.html
Copyright © 2011-2022 走看看