zoukankan      html  css  js  c++  java
  • python操作mysql

    操作mysql的步骤:

    1、建立数据库链接

    2、在链接上建一个游标

    3、执行sql

    4、关闭游标、数据库链接

    e.g:

    import pymysql
    ip = 'any_ip'
    port = 3336
    passwd = '123456'
    user = 'python'
    db = 'test'
    conn = pymysql.Connect(host=ip,user=user,passwd=passwd,port =port,db =db,charset = 'utf8')
    #建立数据库链接 cur
    = conn.cursor(cursor=pymysql.cursors.DictCursor)#指定游标的类型是字典 conn.cursor()默认的类型是元祖 sql1 = 'select * from duguanglong' sql = 'insert into duguanglong(id,name,sex) VALUES(10,"iii","nv")' cur.excute(sql1) print(cur.fetchall)#获取mysql的所有执行结果返回一个列表,fetchone:返回一个字典,只获取第一条数据,如果多次执行就一次往下取 如果是insert/update/del语句就必须commit一下才能执行
    #conn.commit
    cur.close()#关闭游标 conn.close()#关闭链接

     下面写一个操作mysql的函数:

    import pymysql
    def Opertion_mysql(host,user,passwd,db,sql,port=3336,charset='utf8')
      conn = pymysql.Connect(host =host,user=user,passwd=passwd,db=db,port=port,charset=charset )
      cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
      cur.excute(sql)
      if sql.startswith('select'):
          res = cur.fetchone()#
      else:
          conn.commit()
          return  8888#随机定义一个返回值
      cur.close()
      conn.close()
      return res
    #cur.fetch()   他一直返回一个二位的list,不管指定了深了类型的游标(不指定就是元祖 ,制定Diction就是list)
    #cur.fetch 返回字典,且只返回一条数据
      
    if __name__ = '__main__':
      sql1 = 'select * from duguanglong limit 3'
      sql2 ="update duguanglong set name = 'shuaige' where id = 5"
      sql3 ="delete from duguanglong where id =5"
      s =Operation_mysql(host='any_host',user='python',passwd='123456',db='test',sql=sql1,port=3336)
      print(s)
     
  • 相关阅读:
    移动web图片高度自适应的解决方案
    高性能滚动 scroll 及页面渲染优化
    Web学习之跨域问题及解决方案
    apply和call用法
    ES6学习之箭头函数
    JS 对象封装的常用方式
    为Array对象添加一个去除重复项的方法
    最全的常用正则表达式大全
    前端如何实现图片懒加载(lazyload) 提高用户体验
    菜鸟教程 Missing parentheses in call to 'print'
  • 原文地址:https://www.cnblogs.com/lingxia/p/7552361.html
Copyright © 2011-2022 走看看