python操作mysql范例(增删查改)

来源:互联网 发布:淘宝代销怎么样 编辑:程序博客网 时间:2024/05/29 11:59
1 python连接mysql简介
    MySQLdb为Python提供了MySQL支持,它符合Python DB API版本2.0的要求,可在http://sourceforge.net/projects/mysql-python/上找到它。
    用户手册参考地址:http://mysql-python.sourceforge.net/MySQLdb.html
    api参考地址:http://mysql-python.sourceforge.net/MySQLdb-1.2.2/
2 测试环境准备
    操作系统:Red Hat Enterprise Linux Server release 6.4 
    mysql版本:mysql-5.5.28
    查看是否安装MySQL-python
[root@VLAN23-RHEL64-BOC-HA1 ~]# rpm -qa|grep MySQL-pythonMySQL-python-1.2.3-0.3.c1.1.el6.x86_64
    已安装无需理会,未安装的话运行如下安装命令
yum install MySQL-python 
3 编程实例
#!/usr/bin/env python#encoding=utf8import MySQLdbconn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='jesse', port=3355, charset='utf8')cursor = conn.cursor()cursor.execute("drop database if exists tmpdb")cursor.execute("create database tmpdb")conn.select_db("tmpdb")cursor.execute("create table tmptab(c1 int, c2 varchar(20), c3 varchar(20))")cursor.execute("insert into tmptab values(101, '姓名1', 'address1'), (102, '姓名2', 'address2'), (103, '姓名3', 'address3'), (104, '姓名4', 'address4')")conn.commit();#执行commit后数据才能入库并可见cursor.execute("select * from tmptab")print "--增加数据测试--"result = cursor.fetchall()print type(result)for column in result:    print column[0], column[1], column[2]    #print columni #打印全部结果集(中文输出为指针,暂不用此方法)cursor.execute("delete from tmptab where c1 = 101")cursor.execute("select * from tmptab")print "--删除数据测试--"for column in result:    print column[0], column[1], column[2]cursor.execute("update tmptab set c3 = 'address4' where c1 = 103")cursor.execute("select * from tmptab")print "--更新数据测试--"result = cursor.fetchall()for column in result:    print column[0], column[1], column[2]cursor.execute("delete from tmptab")cursor.execute("select * from tmptab")print "--清空数据测试--"result = cursor.fetchall()for column in result:    print column[0], column[1], column[2]cursor.execute("drop table tmptab")cursor.execute("drop database tmpdb")cursor.close()    #关闭指针conn.close()      #关闭连接
默认mysqldb结果集返回的是元组,这样对使用者不太友好,也不利于维护
4 运行脚本
[root@localhost /]# python MysqlPythonTest.py 


5 补充知识

    5.1 python对mysql的查询操作

    fetchone(): 接收结果集的一行
    fetchmany(num): 接收结果集返回的num行,如果num>=结果集的所有行,则同fetchall()
    fetchall():接收结果集全部的返回行.

    5.2 python对mysql的写入操作

    sql语句的入库操作执行后还需要执行conn.commit();才可提交。

    事务机制可以确保数据一致性。
    事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。
    原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
    一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
    隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
    持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。
    Python DB API 2.0 的事务提供了两个方法 commit 或 rollback

6 一些注意事项

    6.1 语言缩进

    Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的Python程序员,也可能陷入陷阱当中。最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分别的。
    在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。该缩进的地方就要缩进,不缩进反而会出错,,比如:
    if xxxxxx:
    (空格)xxxxx
    或者
    def xxxxxx:
    (空格)xxxxx
    还有
    for xxxxxx:
    (空格)xxxxx
    有冒号的下一行往往要缩进

    6.2 python与mysql中文乱码

    为确保程序写入数据库以及从数据库读出时不出现乱码,需要做如下配置:

    python客户端程序级别:

    Python程序文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)

    Python连接MySQL时加上参数 charset=utf8 

    设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)  (可选)

    mysql数据库级别:

    设置MySQL数据库客户端及服务端配置为utf8 

    例如:

    在my.cnf配置文件中配置

[mysql]default_character_set=utf8[mysqld]character-set-server=utf8collation-server=utf8_bin

****************************************************************************************
    原文地址:http://blog.csdn.net/jesseyoung/article/details/40377737
    博客主页:http://blog.csdn.net/jesseyoung
****************************************************************************************

0 0