zoukankan      html  css  js  c++  java
  • Python学习之==>操作MySQL

    一、简介:

      MySQL为关系型数据库,其他关系型数据库包括Oracle、DB2、Sql Server等等。Python操作MySQL需要使用到pymsyql模块,pip安装即可。

    二、操作MySQL步骤

      1、连上数据库(IP、端口号、用户名、密码、数据库名)

      2、建立游标

      3、执行sql

      4、获取结果

      5、关闭游标

      6、关闭连接

     1 import pymysql
     2 conn = pymysql.connect(
     3     host='192.168.1.112',
     4     user='test',
     5     passwd='111111',
     6     port=3306,          # port必须是int类型
     7     db='test',
     8     charset='utf8'      # charset必须写utf8,不能写utf-8
     9 )
    10 sqla = 'select * from stu limit 10;'
    11 sqlb = 'insert into stu (id,name,sex) VALUE (10000,"张流量","女");'
    12 cur = conn.cursor()     # 建立游标,不指定cursor类型返回的是二维元组
    13 cur = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 建立游标,指定cursor类型返回的是字典
    14 cur.execute(sqla)       # 执行sqla
    15 cur.execute(sqlb)       # 执行sqlb
    16 conn.commit()           # 执行insert、delete、update语句必须commit
    17 res = cur.fetchall()    # 执行所有返回的结果,fetchall返回的是一个二维数组
    18 res = cur.fetchone()    # 执行所有返回的结果,fetchone返回的是第一行
    19 res = cur.fetchmany(2)  # 执行所有返回的结果,fetchmany传入一个数返回多少条数据
    20 res = cur.description   # 返回表中每个字段的信息,description返回的也是一个二维数组
    21 print(res)
    22 cur.close()             # 关闭游标
    23 conn.close()            # 关闭连接

     Cursor类型:

      不指定cursor类型,即:cur = conn.cursor(),则返回的结果是:((5, 'Ben', 男'), (6, 'Lily', 女')),是一个二维的元组

      指定curson类型,即:cur = conn.cursor(cursor=pymysql.cursors.DictCursor),则返回的结果是:

      [{'id': 5, 'name': 'Ben', 'sex': '男'}, {'id': 6, 'name': 'Lily', 'sex': '女'}]

    fetchall()和fetchone()的区别:

      fetchall():获取到这个sql执行的全部结果,它把数据库表中的每一行数据放到一个元组或字典里面

      fetchone():获取到这个sql执行的一条结果,它返回的只是一条数据

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

    三、封装操作MySQL数据库的函数

     1 def my_db(sql,port=3306,charset='utf8'):
     2     import pymysql
     3     host,user,passwd,db = '192.168.1.112','test','111111','test'  # 定义变量
     4     conn = pymysql.connect(host=host,
     5                            user=user,
     6                            passwd=passwd,
     7                            port=port,
     8                            db=db,
     9                            charset=charset)
    10     cur = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 建立游标,指定cursor类型返回的是字典
    11     cur.execute(sql)     # 执行语句
    12     if sql.strip().split()[0].upper() == 'SELECT':        # 判断sql语句是否以select开头
    13         res = cur.fetchall()
    14     else:
    15         conn.commit()
    16         res = 'OK'
    17     cur.close()         # 关闭游标
    18     conn.close()        # 关闭连接
    19     return res

     四、练习

      传入一个表名,把所有数据导出,写入excel文件

     1 def export_excel(table_name):
     2     import pymysql,xlwt
     3     conn = pymysql.connect(
     4         host='118.24.3.40',
     5         user='jxz',
     6         passwd='123456',
     7         port=3306,
     8         db='jxz',
     9         charset='utf8')
    10     sql = 'select * from %s;'%table_name
    11     cur = conn.cursor()        # 建立游标,不指定cursor类型返回的是二维元组
    12     cur.execute(sql)           # 执行sql
    13     all_data = cur.fetchall()  # 获取表中所有数据
    14     fileds = [filed[0] for filed in cur.description]  # 获取表的所有字段存入一个list里面
    15     book = xlwt.Workbook()               # 新建一个excel
    16     sheet = book.add_sheet('sheet1')     # 增加sheet页
    17     for col,filed in enumerate(fileds):  
    18         sheet.write(0,col,filed)         # 将表头写入excel文件中的第一行
    19     row = 1                 # 定义行数
    20     for data in all_data:   # 控制行
    21         for col,filed in enumerate(data):#控制列
    22             sheet.write(row,col,filed)
    23         row = row + 1       # 每次写完一行,行加1
    24     book.save('%s.xls'%table_name)
  • 相关阅读:
    笔记(二) C#sql语句
    [叩响C#之门]写给初学者:多线程系列(七)——互锁(Interlocked类)
    C# Async与Await的使用
    C#线程锁使用全功略
    一个C#的加锁解锁示例
    【分析】浅谈C#中Control的Invoke与BeginInvoke在主副线程中的执行顺序和区别(SamWang)
    Control.BeginInvoke()和delegate的BeginInvoke()的区别
    crm04 action操作 和 多级过滤
    VIM和sed 替换字符串方法
    解决Centos关闭You have new mail in /var/spool/mail/root提示(转)
  • 原文地址:https://www.cnblogs.com/L-Test/p/9200545.html
Copyright © 2011-2022 走看看