python操作mysql

import pymysql
coon=pymysql.connect(
    host='xx.xx.xx.xx',user='jxz',passwd='123456',
    port=3306,db='jxz',charset='utf8'
    #port必须写int类型
    #charset必须写utf8
)#建立数据库连接
cur=coon.cursor()#建立游标
cur.execute('select * from stu;')
# cur.execute('insert into stu(id,name,sex) VALUE (1223,"焦哥","男");')
# cur.execute('insert into stu (id,name,sex) VALUE (1,"牛","女");')
coon.commit()   #增删改必须的commit
res=cur.fetchall() #获取所有返回结果
print(res)
cur.close() #关闭游标
coon.close() #关闭连接
import pymysql
def my_db(sql,port=3306,charset='utf8'):
    import pymysql
    host,user,passwd,db='xx.xx.xxxx','jxz','123456','jxz'  #可以多个变量直接一行定义
  coon=pymysql.connect(user=user,host=host,port=port,passwd=passwd,db=db,charset=charset)
    cur=coon.cursor(cursor=pymysql.cursors.DictCursor)#建立游标,指定cursor类型返回的是字典
    cur.execute(sql)

    if sql.strip()[:6].upper()=='SELECT':   #判断sql语句是否select开头
        res = cur.fetchall()
       # fileds = []
      # for filed in cur.description:
      #  fileds.append(filed[0])
        fileds=[filed[0] for filed in cur.description]#和上面3行代码的意思是一样
        print(fileds)
        cur.fetchmany()  #能传入一个数,返回多少条数据
        # res='xx'
        print(res)
    else:
        coon.commit()
        res='ok'
    cur.close() #关闭游标
    coon.close() #关闭连接
res=my_db('select * from users_info;')
print(res)

 

 

 

posted @ 2018-05-04 17:20  小静学测试  阅读(164)  评论(0编辑  收藏  举报