python操作数据库

 1、操作Mysql:

1、Python3安装pymysql第三方模块

   Python2中是MySQLdb模块。

   Python3总没有MySQLdb模块了,所以使用pymysql

2、操作Mysql数据库

  (1) 创建连接,指定数据库的ip地址,账号、密码、端口号、要操作的数据库、字符集

  (2) 创建游标

  (3) 执行sql

  (4) 获取结果

  (5) 关闭游标

  (6) 连接关闭

import pymysql
# 1、连上数据库  账号、密码 ip 端口号 数据库
#2、建立游标
#3、执行sql
#4 、获取结果
# 5、关闭游标
#6、连接关闭
data=[]
coon = pymysql.connect(
    host='IP',user='root',passwd='123456',
    port=3306,db='jxz',charset='utf8'
    #port必须写int类型,
    #charset这里必须写utf8
)
cur = coon.cursor() #建立游标
cur.execute('select * from stu;')#执行sql语句
#cur.execute('insert into stu (id,name,sex) VALUE (1,"小红","女");')
col_name_list = [tuple[0] for tuple in cur.description]
#cur.execute("PRAGMA table_info(stu)")
data.append(col_name_list)
for data1 in cur.fetchall():
    data.append(data1)
#coon.commit()  #必须得coomit
#res = cur.fetchall()  #获取所有返回的结果
#print(len(res))
#data.append(res)
print(data)
print(type(data[0]))
print(type(data[1]))
#print(res)
cur.close()#关闭游标
coon.close()#关闭连接

封装成函数:

def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
    import pymysql
    coon = pymysql.connect(user=user,
                           host=host,
                           port=port,
                           passwd=passwd,
                           db=db,
                           charset=charset
                           )
    cur = coon.cursor() #建立游标
    cur.execute(sql)#执行sql
    if sql.strip()[:6].upper()=='SELECT':
        res =  cur.fetchall()
    else:
        coon.commit()
        res = 'ok'
    cur.close()
    coon.close()
    return res

 (1)

cur = coon.cursor(cursor=pymysql.cursors.DictCursor)
建立游标的时候指定了游标类型,返回的就是一个字典了。

(2)
fetchall() #获取到这个sql执行的全部结果,它把数据库表里面的每一行数据放到一个list里面
[ ['1','2','3'] ] [{},{},{}]
fetchone() #获取到这个sql执行的一条结果,它返回就只是一条数据

如果sql语句执行的结果是多条数据的时候,那就用fetchall()
如果你能确定sql执行的结果就只有一条,那么就用fetchone()

import pymysql
def my_db(sql,port=3306,charset='utf8'):
    import pymysql
    host, user, passwd, db = 'ip','root','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)#执行sql
    if sql.strip()[:6].upper()=='SELECT':
        fileds = [ filed[0] for filed in cur.description ]  #和上面3行代码的意思是一样
        print(fileds)  #['id', 'username', 'passwd']
        #res=cur.fetchall()#获取所有的数据#
        #res=cur.fetchone()#获取一条数据
        #res=cur.fetchmany(2)  #能传入一个数,返回多少条数据
        #res= 'xx'
    else:
        coon.commit()
        res = 'ok'
    cur.close()
    coon.close()
    return res
res = my_db('select * from users_info limit 10;')
print(res)

 (3)

需求:只要你传入一个表名,就能把所有的数据导入出来,字段名是excel的表头
1、要动态获取到表的字段 cur.description能获取到表的字段
fileds = [ filed[0] for filed in cur.description ]
2、获取数据了 select * from "%s" % table_name
3、循环写入excel

enumerate([list,list2]) #循环的时候,直接获取到下标,和值
for index,value in enumerate([list,list2]):
print(index,vlaue)

 通用写入Excel:

import  pymysql,xlwt
def export_excel(table_name):
    host, user, passwd, db = 'ip', 'root', '123456', 'jxz'
    coon = pymysql.connect(host=host, user=user, passwd=passwd, db=db, port=3306, charset='utf8')
    cur = coon.cursor()
    sql='select * from %s ;'%table_name
    cur.execute(sql)
    fileds = [filed[0] for filed in cur.description]
    all_data=cur.fetchall()
    book=xlwt.Workbook()
    sheet=book.add_sheet('stu')
    for index, filed in enumerate(fileds):
        sheet.write(0,index,filed)
    row=1#行数
    for data in all_data:#
        for col,filed in enumerate(data):#控制列
            sheet.write(row,col,filed)
        row+=1#每次写完一行,行数加1
    book.save('%s.xls'%table_name)
    cur.close()
    coon.close()
export_excel('app_student')
原文地址:https://www.cnblogs.com/hwtfamily/p/8982836.html