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()(编辑:雷林鹏 来源:网络|侵删)

  • 相关阅读:
    Centos PHP+Apache执行exec()等Linux脚本权限设置的详细步骤
    新版本的bettercap不好用, 如何安装和编译旧版本的bettercap
    iqiyi__youku__cookie_设置
    window系统命令行设置proxy----Setting a proxy for Windows using the command-line
    修改Electron的libcc(libchromiumcontent)源码,重新编译electron, 设置event.isTrusted为true
    apache配置伪静态Rewrite
    sql注入工具:sqlmap命令
    Reject insecure SameSite=None cookies
    Spring Session Session Max Inactive Interval
    nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
  • 原文地址:https://www.cnblogs.com/pengpeng1208/p/12567032.html
Copyright © 2011-2022 走看看