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)
 

 

posted @ 2017-09-19 16:05  D.零下的小书屋  阅读(158)  评论(0编辑  收藏  举报