使用Python来对MySQL数据库进行操作


使用Python对Mysql进行操作,前提是安装了python-Mysql的安装包,安装的方法有多种,可以使用easy_install或者pip  或者是源码进行安装。
 
下面介绍下如何使用Python对Mysql进行操作,下面是一些简单的例子:
 
(1).使用Python连接MySQL:
 
1 import MySQLdb
3 try:
4     conn = MySQLdb.connect(host="localhost",,user='root',passwd="sina.com",db="mysql",port=3307)
5 except MySQLdb.OperationalError,e:
6     print "the error msg is :",e
(2).使用Python查询MySQL数据:
 
 
 1 import MySQLdb
 2  
 3 try:
 4     conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
 5     cur=conn.cursor()
 6     cur.execute('select * from user')
 7     cur.close()
 8     conn.close()
 9 except MySQLdb.Error,e:
10      print "Mysql Error %d: %s" % (e.args[0], e.args[1])
 
(3).使用Python添加和更新MySQL数据:
 
 
 1 import MySQLdb
 2  
 3 try:
 4     conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
 5     cur=conn.cursor()
 6      
 7     cur.execute('create database if not exists python')
 8     conn.select_db('python')
 9     cur.execute('create table test(id int,info varchar(20))')
10      
11     value=[1,'hi rollen']
12     cur.execute('insert into test values(%s,%s)',value)
13      
14     values=[]
15     for i in range(20):
16         values.append((i,'hi rollen'+str(i)))
17          
18     cur.executemany('insert into test values(%s,%s)',values)
19  
20     cur.execute('update test set info="I am rollen" where id=3')
21  
22     conn.commit()
23     cur.close()
24     conn.close()
25  
26 except MySQLdb.Error,e:
27      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()
     
    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])
 
(4).经常使用的一些API方法:
 
 1 commit() 提交
 2 rollback() 回滚
 3 
 4 cursor用来执行命令的方法:
 5 callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
 6 execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
 7 executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
 8 nextset(self):移动到下一个结果集
 9 
10 cursor用来接收返回值的方法:
11 fetchall(self):接收全部的返回结果行.
12 fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
13 fetchone(self):返回一条结果行.
14 scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.

评论关闭