Python 使用MySQLdb操作 MySQL数据库
引言:本文主要介绍通过MySQLdb实现Python对MySQL数据库的访问和操作。
一、MySQLdb安装:
>>> import sys >>> sys.version '2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)]' >>> import MySQLdb >>>
导入MySQLdb时没有报错,则MySQLdb成功安装
二、MySQLdb的使用大致包括四个步骤:
1)导入MySQLdb模块 import
2)建立连接 connect
3)操作数据库 update、insert、delete、create、select...
4)关闭连接 close
三、一个简单的例子:
>>> import MySQLdb >>> conn = MySQLdb.connect(host='localhost',user='root',passwd='******') >>> cursor = conn.cursor() >>> cursor.execute("SELECT VERSION()") 1L >>> row = cursor.fetchone() >>> print 'mysql version:',row[0] mysql version: 5.1.41 >>> cursor.close() >>> conn.close() >>>
备注:execute 把一条查询语句发送给mysql服务器,这里有两种情况:
1)CREATE、INSERT、DELETE、UPDATE、DROP等没有返回结果的情况,语句直接被执行。
2)对于SELECT等有返回结果的情况,用cursor.fetchone()、cursor.fetchmany(n)、cursor.fetchall()获取返回的结果,结果集的每一行作为一个元组(tuple)返回。
四、一个例子展示常用的CREATE、INSERT、DELETE、UPDATE、SELECT语句。
1 #encoding=utf8 2 #author:edeng.zheng 3 #date:2013-10-20 4 5 import sys 6 import MySQLdb 7 #define the connection param 8 hostname='localhost' 9 username='root' 10 password='********' 11 dbname='test' 12 tbname='mytest' 13 port= 3306 14 charset='utf8' 15 try: 16 conn = MySQLdb.connect( 17 host=hostname, 18 user=username, 19 passwd=password, 20 db=dbname, 21 port=port, 22 charset=charset, 23 ) 24 cursor = conn.cursor() 25 #如果表已经存在,则删除· 26 cursor.execute("""DROP TABLE IF EXISTS %s""" % (tbname,)) 27 #创建表 28 cursor.execute("""CREATE TABLE IF NOT EXISTS %s( 29 id int(11) not null auto_increment, 30 name char(20) not null, 31 PRIMARY KEY(id) 32 )ENGINE=MyISAM; 33 """ % (tbname,)) 34 35 36 #向刚创建的表中插入数据 37 cursor.execute(""" 38 INSERT INTO %s (name) 39 VALUES 40 ('Monday'),('Thesday'),('Wednesday'),('Thursday'),('Friday'),('Saturday'),('Sunday'); 41 """ % (tbname,)) 42 43 #获取所有查询结果 44 print 'fetchall():' 45 cursor.execute(""" 46 SELECT * FROM %s; 47 """ % (tbname,)) 48 res = cursor.fetchall() 49 for k in res: 50 print 'id %d:%s' % (k[0],k[1]) 51 52 #获取3条查询结果 53 print 'fetchmany():N=3' 54 cursor.execute(""" 55 SELECT * FROM %s; 56 """ % (tbname,)) 57 res = cursor.fetchmany(3) 58 for k in res: 59 print 'id %d:%s' % (k[0],k[1]) 60 61 #获取一条查询结果 62 print 'fetchone()' 63 cursor.execute(""" 64 SELECT * FROM %s; 65 """ % (tbname,)) 66 res = cursor.fetchone() 67 print res[0],res[1] 68 print cursor.rowcount 69 70 #删除一条数据 71 cursor.execute(""" 72 DELETE FROM %s WHERE id = 1; 73 """ % (tbname,)) 74 print cursor.rowcount 75 76 77 #更新一条数据 78 cursor.execute(""" 79 UPDATE %s SET name='Congratulations!' WHERE id=2 80 """ % (tbname,)) 81 82 cursor.close() 83 84 #创建一个字典型的游标,这样可以用名称访问,而不通过下表访问 85 cursor = conn.cursor(MySQLdb.cursors.DictCursor) 86 cursor.execute(""" 87 SELECT * FROM %s WHERE id = 5; 88 """ % (tbname,)) 89 row = cursor.fetchone() 90 print row['name'] 91 92 #关闭游标 93 cursor.close() 94 #关闭连接 95 conn.close() 96 except MySQLdb.Error,e: 97 print 'mysql error %d:%s',(e.args[0],e.args[1]) 98 sys.exit()
五:扩展阅读:

浙公网安备 33010602011771号