• python类库26[读写mysql]


    一 MySQL模块安装

    下载:http://sourceforge.net/projects/mysql-python
    安装: 
           python setup.py build (源码安装)
           python setup.py install

    支持:目前支持MySQL versions 3.23-5.1和Python versions 2.3-2.6

    二 MySQL操作过程

    1)import MySQLdb

    导入MySQLdb模块。

    2)conn = MySQLdb.connect()

    使用connect()来连接MySQL数据库,connect()用来和数据库建立连接,接收数个参数,返回连接对象. 比较常用的参数包括 
    host:数据库主机名.默认是用本地主机. 
    user:数据库登陆名.默认是当前用户. 
    passwd:数据库登陆的秘密.默认为空. 
    db:要使用的数据库名.没有默认值. 
    port:MySQL服务使用的TCP端口.默认是3306.
    charset:数据库编码,一般为utf8.

    3)cursor=conn.cursor();n=cursor.execute(sql,param);cursor.fetchall ()

    首先,我们用使用连接对象conn获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.

    这些方法包括两大类:1.执行命令,2.接收返回值 

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

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


    4)conn.commit() or conn.rollback()

    对事务操作的支持。

    游标cursor提供了一种对从表中检索出的数据进行操作的灵活手段,就本质而言,游标实际上是一种能从包括多条数据记录的结果集中每次提取一条记录的机制。游标总是与一条T_SQL 选择语句相关联因为游标由结果集和结果集中指向特定记录的游标位置组成。当决定对结果集进行处理时,必须声明一个指向该结果集的游标。 

    5)cursor.close(); conn.close() 
    关闭cursor和数据库的链接conn。

    三 MySQL实例 

       #!/usr/bin/python
       # animal.py - create animal table and
       # retrieve information from it

       
    import sys
       
    import MySQLdb

       
    # connect to the MySQL server

       
    try:
         conn 
    = MySQLdb.connect (host = "localhost",
                                 user 
    = "testuser",
                                 passwd 
    = "testpass",
                                 db 
    = "test")
       
    except MySQLdb.Error, e:
         
    print "Error %d: %s" % (e.args[0], e.args[1])
         sys.exit (
    1)

       
    # create the animal table and populate it

       
    try:
         cursor 
    = conn.cursor ()
         cursor.execute (
    "DROP TABLE IF EXISTS animal")
         cursor.execute (
    """
             CREATE TABLE animal
             (
               name     CHAR(40),
               category CHAR(40)
             )
           
    """)
         cursor.execute (
    """
             INSERT INTO animal (name, category)
             VALUES
               ('snake', 'reptile'),
               ('frog', 'amphibian'),
               ('tuna', 'fish'),
               ('racoon', 'mammal')
           
    """)
         
    print "Number of rows inserted: %d" % cursor.rowcount

       
    # perform a fetch loop using fetchone()

         cursor.execute (
    "SELECT name, category FROM animal")
         
    while (1):
           row 
    = cursor.fetchone ()
           
    if row == None:
             
    break
           
    print "%s, %s" % (row[0], row[1])
         
    print "Number of rows returned: %d" % cursor.rowcount

       
    # perform a fetch loop using fetchall()

         cursor.execute (
    "SELECT name, category FROM animal")
         rows 
    = cursor.fetchall ()
         
    for row in rows:
           
    print "%s, %s" % (row[0], row[1])
         
    print "Number of rows returned: %d" % cursor.rowcount

       
    # issue a statement that changes the name by including data values
       # literally in the statement string, then change the name back
       # by using placeholders

         cursor.execute (
    """
               UPDATE animal SET name = 'turtle'
               WHERE name = 'snake'
             
    """)
         
    print "Number of rows updated: %d" % cursor.rowcount

         cursor.execute (
    """
               UPDATE animal SET name = %s
               WHERE name = %s
             
    """, ("snake""turtle"))
         
    print "Number of rows updated: %d" % cursor.rowcount

       
    # create a dictionary cursor so that column values
       # can be accessed by name rather than by position

         cursor.close ()
         cursor 
    = conn.cursor (MySQLdb.cursors.DictCursor)
         cursor.execute (
    "SELECT name, category FROM animal")
         result_set 
    = cursor.fetchall ()
         
    for row in result_set:
           
    print "%s, %s" % (row["name"], row["category"])
         
    print "Number of rows returned: %d" % cursor.rowcount

         cursor.close ()

       
    except MySQLdb.Error, e:
         
    print "Error %d: %s" % (e.args[0], e.args[1])
         sys.exit (
    1)

       conn.commit ()
       conn.close ()

    四 解决中文乱码问题

    1) Python文件设置编码utf-8 (文件前面加上 #encoding=utf-8 或 #-*- coding: utf-8 -*-)
    2) MySQL数据库charset=utf-8  (my.conf中的client和mysqld中均需要设为utf-8)
    3) Python连接MySQL是加上参数 charset=utf8
    4) 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

    参考:

    http://drizzlewalk.blog.51cto.com/2203401/448874

    http://www.kitebird.com/articles/pydbapi.html

    完!


    作者:iTech
    微信公众号: cicdops
    出处:http://itech.cnblogs.com/
    github:https://github.com/cicdops/cicdops

  • 相关阅读:
    关于ajax入门案例
    关于idea maven工程创建struts2入门配置及案例
    hibernate关于多对多注解配置
    hibernate关于一对一注解配置
    hibernate批量处理数据
    HQL链接查询
    关于hibernate组件配置
    VS2010 项目属性的默认包含路径设置方法
    VC++的全局变量(转)
    调用文字在位编辑器
  • 原文地址:https://www.cnblogs.com/itech/p/1924973.html
Copyright © 2020-2023  润新知