python操作MySQL数据库

MySQLdb呢,其实和Python内置的sqlite3的使用方法基本相同。

警告:

    不要使用字符串拼接生成SQL语句,否则可能产生SQL注入的问题。应当使用 execute() 的第二个参数检查输入的合法性。

#do NOT do this!
cmd = "update people set name='%s' where id='%s'" % (name, id) 
cur.execute(cmd)
# instead, do this: cmd = "update people set name=%s where id=%s"
cur.execute(cmd, (name, id))

采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧:

import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='mysql',db='test',port=3306)
    cur=conn.cursor()
    cur.execute('select * from user')
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

请注意修改你的数据库,主机名,用户名,密码。

下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:

import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()
     
    cur.execute('create database if not exists python')
    conn.select_db('python')
    cur.execute('create table test(id int,info varchar(20))')
     
    value=[1,'hi rollen']
    cur.execute('insert into test values(%s,%s)',value)
     
    values=[]
    for i in range(20):
        values.append((i,'hi rollen'+str(i)))
         
    cur.executemany('insert into test values(%s,%s)',values)
 
    cur.execute('update test set info="I am rollen" where id=3')
 
    conn.commit()
    cur.close()
    conn.close()
 
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

游标相当于是集合中元素的指针,SQL查询结果是一个集合,而线程每次只能获得一个元素的引用。游标也必须要关闭,否则会占用有限的资源

有些界面可以自动提交。但是对于python的MySQLdb模块,必须要调用commit(), 否则所有的更新只对于当前连接有效,数据库并不会实际被更改。

每插入一次就要commit一次! 具体见本文最后。

import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()
     
    conn.select_db('python')
 
    count=cur.execute('select * from test')
    print 'there has %s rows record' % count
 
    result=cur.fetchone()
    print result
    print 'ID: %s info %s' % result
 
    results=cur.fetchmany(5)
    for r in results:
        print r
 
    print '=='*10
    cur.scroll(0,mode='absolute')
 
    results=cur.fetchall()
    for r in results:
        print r[1]
     
 
    conn.commit()
    cur.close()
    conn.close()
 
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

查询后中文会正确显示,但在数据库中却是乱码的。

网上的说法是加一个属性,不过经过本人实验,这并不能解决问题,反而让打印出来的中文全是问号。

在Python代码 

conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
 改为:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8') 
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。

常用函数

下面贴一下常用的函数:

然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚

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条.

字典而非元组

MySQLdb默认情况下,查询结果行都是返回tuple,访问的时候不是很方便,必须按照0,1这样读取。

使用sqllite3的时候,可以修改过Connection对象的row_factory属性,以便使用sqlite3.Row,这样结果集中的数据行就是字典形式的,可以用字段名访问,那么MySQLdb中是不是也有这样的方法呢?MySQLdb中有DictCursor,要做到这点也很简单,那就是建立数据库连接是传递cusorclass参数,或者在获取Cursor对象时传递cusorclass参数即可:
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8",cursorclass=MySQLdb.cursors.DictCursor)  
cursor = conn.cursor()  
或者
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")  
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)  

返回结果就是这样:

{'name': u'ccc', 'created': 33L}
{'name': u'ddd', 'created': 44L}
{'name': u'zzz', 'created': 1340790602L}

MySQL中的事务

事务支持

首先要了解到,Innodb支持事务, MyISAM不支持事务。

而且mysql的事务是默认是打开autocommit的,但是我们使用的python库,mysqldb却是默认关闭autocommit,所以你需要自己去commit,自己去rollback。

回到问题

任何时候,在执行提交或者回滚操作之前,所有的操作都会被数据库认为属于同一个事务,

MySQL事务的默认隔离级别是repeatable read(重复读),而这却会引起phantom read(幻想读)。

幻像读(phantom read):在同一事务中,同一查询多次进行时候,由于其他插入操作(insert)的事务提交,导致每次返回不同的结果集。

而innodb为了防止幻读,会在一个事务中,使所有select的结果保持与第一次select时的snapshot一致,这样其他事务的插入是不会被感知到的。

所以对于一个只有读的事务,我们也应该及时提交后再读,使snapshot刷新。

原文地址:https://www.cnblogs.com/xinchrome/p/5011781.html