python关于Mysql操作

发布时间:2019-08-07 13:52:57编辑:auto阅读(1607)

    一.安装mysql

    windows下,直接下载mysql安装文件,双击安装文件下一步进行操作即可,

    下载地址:http://dev.mysql.com/downloads/mysql/

    Linux下的安装也很简单,除了下载安装包进行安装外,一般的linux仓库中都会有mysql ,我们只需要通过一个命令就可以下载安装:

    Ubuntu、deepin

    sudo apt-get install mysql-server 

    Sudo apt-get install  mysql-client

    centOS、redhat

    yum install mysql


    二.安装MySQL-python

    要想使python可以操作mysql 就需要MySQL-python驱动,它是python 操作mysql必不可少的模块。

    下载地址:http://dev.mysql.com/downloads/connector/python/

    下载后直接双击安装文件下一步操作即可。


    三.测试是否安装成功

    执行以下语句看是否报错,不报错说明MySQLdb模块安装成功

    import MySQLdb


    四.Mysql基本操作

    查看当前所有的数据库

    show databases;


    选择数据库

    use test;


    查看test库下面的表

    show tables;


    创建msg表,包括id、title、name、content四个字段

    create table `msg`(

    `id` int primary key auto_increment,

    `title` varchar(60),

    `name` varchar(10),

    `content` varchar(1000)

    );


    向msg表内插入数据

    insert into msg

    (title,name,content)

    values

    ('test01','zhzhgo01','test content01'),

    ('test02','zhzhgo02','test content02'),

    ('test03','zhzhgo03','test content03'),

    ('test04','zhzhgo04','test content04'),

    ('test05','zhzhgo05','test content05');


    查看msg表的数据

    select * from msg;


    修改name等于zhzhgo05的content为test05

    update msg set content='test05' where name='zhzhgo05';


    删除name=zhzhgo05的数据

    delete from msg where name='zhzhgo05';


    给root用户在127.0.0.1这个机器上赋予全部权限,密码为123456,并即时生效

    grant all privileges on *.* to 'root'@'127.0.0.1' identified by '123456';

    flush privileges;


    五.Python操作Mysql数据库

    1.基本操作

    import MySQLdb 

    conn=MySQLdb.connect(host="127.0.0.1",user="root",\

                         passwd="123456",db="test",\

                         port=3306,charset="utf8") 

    connect() 方法用于创建数据库的连接,里面可以指定参数:主机、用户名、密码、所选择的数据库、端口、字符集,这只是连接到了数据库,要想操作数据库还需要创建游标

    cur=conn.cursor() 

    通过获取到的数据库连接conn下的cursor()方法来创建游标

    n=cur.execute(sql,param) 

    通过游标cur操作execute()方法写入sql语句来对数据进行操作,返回受影响的条目数量

    cur.close() 

    关闭游标

    conn.commit()

    提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入

    conn.rollback()

    发生错误时回滚

    conn.close()

    关闭数据库连接


    2.插入数据

    cur.execute("insert into msg (title,name,content) values ('test05','zhzhgo05','test content05')")可以直接插入一条数据,但是想插入多条数据的时候这样做并不方便,此时可以用excutemany()方法,看下面的例子:

    import MySQLdb
    conn=MySQLdb.connect(host="127.0.0.1",user="root",\
                         passwd="123456",db="test",\
                         port=3306,charset="utf8") 
    cur = conn.cursor()
    #一次插入多条记录
    sql="insert into msg (title,name,content) values(%s,%s,%s)"
    #executemany()方法可以一次插入多条值,执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
    cur.executemany(sql,[
        ('test05','zhzhgo05','test content05'),
        ('test06','zhzhgo06','test content06'),
        ('test07','zhzhgo07','test content07'),
        ])
    cur.close()
    conn.commit()
    conn.close()

    如果想要向表中插入1000条数据怎么做呢,显然用上面的方法很难实现,如果只是测试数据,那么可以利用for循环,现有一张user表,字段id自增,性别随机,看下面代码:

    import MySQLdb
    import random
    conn=MySQLdb.connect(host="127.0.0.1",user="root",\
                         passwd="",db="test",\
                         port=3306,charset="utf8")
    cur=conn.cursor()
    sql="insert into user (name,gender) values"
    for i in range(1000):
        sql+="('user"+str(i)+"',"+str(random.randint(0,1))+"),"
    sql=sql[:-1]
    print sql
    cur.execute(sql)


    3.查询数据

    执行cur.execute("select * from msg")来查询数据表中的数据时并没有把表中的数据打印出来,如下:

    import MySQLdb
    conn=MySQLdb.connect(host="127.0.0.1",user="root",\
                         passwd="",db="test",\
                         port=3306,charset="utf8")
    cur=conn.cursor()
    sql='select * from msg'
    n=cur.execute(sql)
    print n

    此时获得的只是我们的表中有多少条数据,并没有把数据打印出来

    介绍几个常用的函数:

    fetchall():接收全部的返回结果行

    fetchmany(size=None):接收size条返回结果行,如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据

    fetchone():返回一条结果行

    scroll(value,mode='relative'):移动指针到某一行,如果mode='relative',则表示从当前所在行移动value条;如果mode='absolute',则表示从结果集的第一行移动value条


    看下面的例子:

    import MySQLdb
    conn=MySQLdb.connect(host="127.0.0.1",user="root",\
                         passwd="",db="test",\
                         port=3306,charset="utf8")
    cur=conn.cursor()
    sql='select * from msg'
    n=cur.execute(sql)
    print cur.fetchall()
    print "-------------------"
    cur.scroll(1,mode='absolute')
    print cur.fetchmany(1)
    print "-------------------"
    cur.scroll(1,mode='relative')
    print cur.fetchmany(1)
    print "-------------------"
    cur.scroll(0,mode='absolute')
    row=cur.fetchone()
    while row:
        print row[2]
        row=cur.fetchone()
    cur.close()
    conn.close()

    执行结果如下:

    >>> 

    ((1L, u'test01', u'zhzhgo01', u'test content01'), (2L, u'test02', u'zhzhgo02', u'test content02'), (3L, u'test03', u'zhzhgo03', u'test content03'), (4L, u'test04', u'zhzhgo04', u'test content04'))

    -------------------

    ((2L, u'test02', u'zhzhgo02', u'test content02'),)

    -------------------

    ((4L, u'test04', u'zhzhgo04', u'test content04'),)

    -------------------

    zhzhgo01

    zhzhgo02

    zhzhgo03

    zhzhgo04

    >>> 


    4.执行事务

    事务机制可以确保数据一致性。事务具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。

    原子性(atomicity):一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。

    一致性(consistency):事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。

    隔离性(isolation):一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。

    持久性(durability):持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。

    Python DB API 2.0的事务提供了两个方法commit或rollback。

    对于支持事务的数据库,在Python数据库编程中,当游标建立之时,就自动开始了一个隐形的数据库事务。commit()方法提交游标的所有更新操作,rollback()方法回滚当前游标的所有操作。每一个方法都开始了一个新的事务。

    如下实例:

    import MySQLdb
    conn=MySQLdb.connect(host="127.0.0.1",user="root",\
                         passwd="",db="test",\
                         port=3306,charset="utf8")
    cur=conn.cursor()
    try:
        # 执行SQL语句
        cur.execute("drop table if exists msg")
        # 向数据库提交
        conn.commit()
    except:
        # 发生错误时回滚
        conn.rollback()
    conn.close()


关键字

上一篇: python-urlparse

下一篇: Python写的小九九