• python MySQLdb pymsql


    参考文档 https://www.python.org/dev/peps/pep-0249/#nextset 

    本节内容

    • MySQLdb 
    • pymysql

    MySQLdb和pymysql分别为Python2和Python3操作MySQL数据库的模块,两个模块的用法基本相同, 这里就把两个模块放到一起说下用Python如何来操作MySQL数据库。

     

    一.MySQLdb的使用

    1.导入模块

    import MySQLdb 

    2.建立连接,获取连接对象

    在建立数据库连接时connect函数中可以接收多个参数,返回的为连接对象

    connect参数说明如下↓

    """
    
    Create a connection to the database. It is strongly recommended
    that you only use keyword parameters. Consult the MySQL C API
    documentation for more information.
    
    host
      string, host to connect
      
    user
      string, user to connect as
    
    passwd
      string, password to use
    
    db
      string, database to use
    
    port
      integer, TCP/IP port to connect to
    
    unix_socket
      string, location of unix_socket to use
    
    conv
      conversion dictionary, see MySQLdb.converters
    
    connect_timeout
      number of seconds to wait before the connection attempt
      fails.
    
    compress
      if set, compression is enabled
    
    named_pipe
      if set, a named pipe is used to connect (Windows only)
    
    init_command
      command which is run once the connection is created
    
    read_default_file
      file from which default client values are read
    
    read_default_group
      configuration group to use from the default file
    
    cursorclass
      class object, used to create cursors (keyword only)
    
    use_unicode
      If True, text-like columns are returned as unicode objects
      using the connection's character set.  Otherwise, text-like
      columns are returned as strings.  columns are returned as
      normal strings. Unicode objects will always be encoded to
      the connection's character set regardless of this setting.
    
    charset
      If supplied, the connection character set will be changed
      to this character set (MySQL-4.1 and newer). This implies
      use_unicode=True.
    
    sql_mode
      If supplied, the session SQL mode will be changed to this
      setting (MySQL-4.1 and newer). For more details and legal
      values, see the MySQL documentation.
      
    client_flag
      integer, flags to use or 0
      (see MySQL docs or constants/CLIENTS.py)
    
    ssl
      dictionary or mapping, contains SSL connection parameters;
      see the MySQL documentation for more details
      (mysql_ssl_set()).  If this is set, and the client does not
      support SSL, NotSupportedError will be raised.
    
    local_infile
      integer, non-zero enables LOAD LOCAL INFILE; zero disables
    
    There are a number of undocumented, non-standard methods. See the
    documentation for the MySQL C API for some hints on what they do.
    
    """
    View Code
    conn = MySQLdb.connect(host='192.168.10.165', port=3306, user='root', passwd='123456', db='center')     # 和数据库建立连接

    3.创建一个游标来进行数据库操作

    游标默认返回的数据类型为tuple,当加入cursorclass=MySQLdb.cursors.DictCursor时,返回的数据类型为dict

    cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

    4.利用游标对象进行数据库操作

    数据操作主要分为执行sql和返回数据

    下面为cursor用来执行命令的方法:

    callproc(self, procname, args)    # 用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数 
    execute(self, query, args)        # 执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数 
    executemany(self, query, args)    # 执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数 
    nextset(self)                     # 移动到下一个结果集 

    executemany处理过多的命令也不见得一定好,因为数据一起传入到server端,可能会造成server端的buffer溢出,而一次数据量过大,也有可能产生一些意想不到的麻烦。合理,分批次executemany是个不错的办法。

    下面为cursor用来接收返回值的方法:

    fetchall(self)      # 接收全部的返回结果行. 
    fetchmany(self, size=None)      # 接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据. 
    fetchone(self)      # 返回一条结果行. 
    scroll(self, value, mode='relative')        # 移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条. 

    接下来看一完整的例子:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    __author__ = '40kuai'
    
    import MySQLdb  # 导入模块
    conn = MySQLdb.connect(host='192.168.10.165', port=3306, user='root', passwd='123456', db='db')     # 和数据库建立连接
    cursor = conn.cursor()  # 获取游标进行数据操作
    # 查询
    effect_row = cursor.executemany("select * from user limit %s ",(10,))  # 返回受影响行数
    print effect_row # 返回为受影响的条数
    print cursor.fetchone()     # 打印一条返回结果
    print ''.center(50,'#')
    print cursor.fetchall()     # 返回所有的数据,这里为剩余的数据
    cursor.scroll(0,mode='absolute')        # 重置游标位置
    print cursor.fetchone()
    
    # 提交,不然无法保存新建或者修改的数据,这里为查询操作可以不写
    conn.commit()
    
    # 关闭游标
    cursor.close()
    # 关闭连接
    conn.close()

    # 输出(大概)
    # 10
    # (10001L,'40kuai',1476858893L)
    # ##################################################
    # ((10002L,'41kuai',1476858893L),......) # 后边数据省略
    # (10001L,'40kuai',1476858893L)

    5.对数据库进行操作时注意事项:

    • 使用sql语句,这里要接收的参数都用%s占位符.要注意的是, 无论你要插入的数据是什么类型,占位符永远都要用%s 
    • param应该为tuple或者list 
    • 使用executemany添加多条数据时,每个传入参数的集合为一个tuple,整个参数组成一个tuple,或者list
    • 返回数据为字典类型可以在创建数据库连接(connection)时传入cursorclass=MySQLdb.cursors.DictCursor,或者在创建游标时(cursor)加入参数cursorclass=MySQLdb.cursors.DictCursor
    • --在conntction中加入cursorclass=MySQLdb.cursors.DictCursor会报错('module' object has no attribute 'cursors'),应该是有与对象还没有实例化没有cursors方法。

    6.查询数据后的一些收尾工作

    在对数据进行操作时需要说明两个函数,commitrollback

      如果使用支持事务的存储引擎,那么每次操作后,commit是必须的,否则不会真正写入数据库(查询操作可以不执行commit),对应rollback可以进行相应的回滚,但是commit后是无法再rollback的。commit() 可以在执行很多sql指令后再一次调用,这样可以适当提升性能。

    # 需要分别的关闭指针对象和连接对象.他们有名字相同的方法 
    cursor.close() 
    conn.close() 
    
    编码:
    Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8) MySQL数据库charset=utf-8 Python连接MySQL是加上参数 charset=utf8 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

    7.一些例子

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    __author__ = '40kuai'
    import time
    import MySQLdb  # 导入模块
    
    conn = MySQLdb.connect(host='192.168.10.165', port=3306, user='root', passwd='123456', db='db',
                           )     # 和数据库建立连接
    conn = set_charset('utf-8')  # 设置字符集 cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) # 获取游标进行数据操作 # 删除表 cursor.execute('drop table if exists user') cursor.execute('create table if not exists user(name varchar(128) primary key, created int(10))') # 添加 effect_row = cursor.execute("insert into user(name,created) values(%s,%s)",("40kuai",int(time.time()))) print 'insert',effect_row # 添加多条 effect_row = cursor.executemany("insert into user(name,created) values(%s,%s)",(("41kuai",int(time.time())),("42kuai",int(time.time())),("43kuai",int(time.time())))) print 'insert',effect_row # 更新 effect_row = cursor.execute("update user set name=%s where created={time}".format(time=time.time()) ,('40kuai')) print 'update',effect_row # 查询 effect_row = cursor.execute("select * from user WHERE name='40kuai'") print cursor.fetchone() #删除 effect_row = cursor.execute("delete from user where name=%s" ,('40kuai')) print 'delete',effect_row # 查询 effect_row = cursor.execute("select * from user") print cursor.fetchall() conn.commit() # 提交,不然无法保存新建或者修改的数据,这里为查询操作可以不写 cursor.close() # 关闭游标 conn.close() # 关闭连接

    8.一些小知识点

    • 如果有自增ID列通过 cursor.lastrowid 来获取最新自增ID
    • 使用cursor.scroll(num,mode)来移动游标位置
        •  cursor.scroll(1,mode='relative')   # 相对当前位置移动
        • cursor.scroll(0,mode='absolute')   # 相对绝对位置移动

    二.pymysql的使用

    pymysql是python3中操作mysql的模块,MySQLdb是python2中操作MySQL的模块,但在用法上和大同小异,这里只是说明下两者的不同

    1.导入方法不同

      正常人都可以理解

    2.在对返回的数据设置为字典类型

      pymysql: cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

      MySQLdb: cursor = conn.cursor(cursorclass=pymysql.cursors.DictCursor)

     

    其他的我也暂时还不知道,以后有的话我再补充。

    最新内容可以看我的blog: 40kuai
  • 相关阅读:
    对.Net Framework的认识(3)
    对负载均衡的认识
    对.Net Framework的认识(1)
    对.Net Framework的认识(2)
    对ASP.Net的认识(二)
    windows 使用 ssh 隧道代理
    python + django 搭建网页(尝试4):自动显示txt文件
    群论基础(3):有限群表示论
    群论基础(1):群的定义
    群论基础(5):李群
  • 原文地址:https://www.cnblogs.com/40kuai/p/7475111.html
Copyright © 2020-2023  润新知