Python 操作MySQL 数据库

要操作MySQL 需要安装MySQLdb 这个包,为了简化操作,在网上找到了Python 2.7 下的安装文件,直接双击exe文件即可。下载地址:http://vdisk.weibo.com/s/aDNfaTygMajaE/1421222658


1. 连接数据库

通过MySQLdb 的connect() 函数即可进行连接,通常需提供的参数如下:

host: 主机地址   <必填>

user: 登录数据库的用户名  <必填>

passwd: 登录密码   <必填>

dbname: 要连接的数据库名  <必填>

port: 默认端口为 3306  [可选 ]

charset:  数据库编码,默认为 latin1 [可选]

如:

conn = MySQLdb.connect (host = 'localhost',
			user = 'jeff',
			passwd = 'jeff2015',
			db = 'test',           # 这个数据库要必须存在,不存在将引发一个错误
			charset = 'utf8')


2. 创建数据库及表

连接数据库后,在操作数据库前,先使用连接对象获得一个cursor对象:

cursor = conn.cursor()

cursor 对象有以下常用方法:
1) callproc(self, procname, args) ,用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
2) execute(self, query, args) ,执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
3) executemany(self, query, args) ,执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
4) nextset(self) ,移动到下一个结果集
5) cursor 接收返回值的方法
6) fetchall(self) ,接收全部的返回结果行
7) fetchallmany(self, size=None) ,接收size 条返回结果行,如果 size的值大于返回结果行的数量,则返回 cursor.arraysize 条数据
8) fetchone(self) ,返回一条结果行
9) scroll(self, value, mode='relative') , 移动指针到某一行,如果 mode='relative',则表示从当前所在行移动 value 条,如果mode='absolute',则表示从结果集的第一行移动到value 条

如下是用 execute 方法来执行一条sql 语句:

cursor.execute("""
		CREATE TABLE animal
		(
		  name CHAR(20),
		  category CHAR(40)
		)
	""")

3. 增、删、改、查

# 增
cursor.execute("""
		INSERT INTO animal (name, category) 
		VALUES
		('snake', 'reptile'),
		('frog', 'amphibian'),
		('tuna', 'fish'),
		('racoon', 'mammal')
	""")

# 删
cursor.execute("""
		DELETE FROM animal
		WHERE name = 'frog'
	""")

# 改
cursor.execute("""
		UPDATE animal SET name = 'turtle'
		WHERE name = 'snake'
	""")


# 查
cursor.execute("SELECT name, category FROM animal")
rows = cursor.fetchall()   # 接收全部的返回值
	for row in rows:   
		print '%s, %s' % (row[0], row[1])
	print 'Number of rows returned: %d' % cursor.rowcount

4. 关闭数据库

需要注意的是,MySQL 默认是自动提交事务的,也就是说不需要手动 commit 来提交事务。但为了确保操作,还是加上。

最后,所有操作完后,需关闭数据库连接:

conn.commit()
conn.close()


5. 中文编码问题

操作数据库内容如果包含中文,需确保以下几件事是被执行的:

1) Python 的文件编码要是 utf-8, #coding:utf-8
2) MySQL 数据库连接编码要是 utf-8, charset=utf-8
3) 数据库本身的编码要是 utf-8  # 这点通常会被忽略

做了以上事情后,即可进行中文的操作:

up = "UPDATE animal SET name = '海龟' 
      WHERE name = 'turtle'"
up = up.decode('gb2312') # 先对字符串进行编码
cursor.execute(up)       


下面给出Python 的完整代码:

#coding:utf-8

import sys
import MySQLdb

# connect to the MySQL server

try:
	conn = MySQLdb.connect (host = 'localhost',
							user = 'jeff',
							passwd = 'jeff2015',
							db = 'test',
							charset = 'utf8')

except MySQLdb.Error, e:
	print 'Error %d: %s' % (e.args[0], e.args[1])
	sys.exit(1)


# create the animal table and populate it
try:
	cursor = conn.cursor()
	
	cursor.execute('DROP TABLE IF EXISTS animal')
	cursor.execute("""
		CREATE TABLE animal
		(
			name CHAR(20),
			category CHAR(40)
		)
	""")
	cursor.execute("""
		INSERT INTO animal (name, category) 
		VALUES
		('snake', 'reptile'),
		('frog', 'amphibian'),
		('tuna', 'fish'),
		('racoon', 'mammal')
	""")

	print 'Number of rows inserted: %d' % cursor.rowcount


	# perform a fetch loop using fetchone()
	cursor.execute("SELECT name, category FROM animal")
	while (1):
		row = cursor.fetchone()
		if row == None:
			break
		print '%s, %s' % (row[0], row[1])
	print "Number of rows returned: %d" % cursor.rowcount

	#perform a fetch loop using fetchall()
	cursor.execute("SELECT name, category FROM animal")
	rows = cursor.fetchall()
	for row in rows:
		print '%s, %s' % (row[0], row[1])
	print 'Number of rows returned: %d' % cursor.rowcount

	# issue a statement that changes the name by including data values
	# literally in the statement string, then change the name back
	# by using placeholders
	up = "UPDATE animal SET name = '海龟' WHERE name = 'snake'"
	up = up.decode('gb2312')
	cursor.execute(up)
	'''
	cursor.execute("""
		UPDATE animal SET name = 'turtle'
		WHERE name = 'snake'
	""")
	'''
	print 'Number of rows updated: %d' % cursor.rowcount

	cursor.execute ("""
		UPDATE animal SET name = %s
		WHERE name = %s
	""", ('snake', 'turtle'))
	print 'Number of rows updated: %d' % cursor.rowcount


	# create a dictionary cursor so that column values
	# can be accessed by name rather than by position
	cursor.close()

except MySQLdb.Error, e:
	print 'Error %d: %s' % (e.args[0], e.args[1])
	sys.exit(1)

conn.commit()
conn.close()


以上参考:http://www.cnblogs.com/itech/archive/2011/01/06/1924973.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值