Python连接MySQL操作

Python很强大啊,不用多说的……这里简单介绍一下其中的一个模块就是DB-API,也就是提供数据库应用编程接口的一个东西。
参考资料:Writing MySQL Scripts with Python DB-API
DB-API两层架构:顶层为所有的数据库引擎提供一个抽象的接口,底层包含特定数据库引擎的驱动等用于处理特定引擎云云。所以,在写Python脚本之前需要先装这个特定的驱动,比如MySQL,就需要安装MySQLdb模块。

第一步:MySQLdb Installation
详见(ubuntu10.04) MySQL-python-1.2.3

第二步:Writing DB-API Script
注意缩进,本文编辑显示不出来,缩进是个老会出错的东西,一定要注意!

Step1–连接MySQL服务器
import MySQLdb
conn = MySQLdb.connect (host = “localhost”,user = “testuser”,passwd = “testpass”,db = “test”)
若connect()调用成功,则返回一个连接对象,可用于后续的数据库操作;若调用失败,则返回一个异常,处理方式如下:
import sys
try:
conn = MySQLdb.connect (host = “localhost”,user = “testuser”,passwd = “testpass”,db = “test”)
except MySQLdb.Error, e:
print “Error %d: %s” % (e.args[0], e.args[1])
sys.exit (1)

Step2–执行语句获取执行结果

cursor = conn.cursor ()
cursor.execute (“SELECT VERSION()”)
row = cursor.fetchone ()
print “server version:”, row[0]

cursor对象将执行结果返回保存到服务器,利用该对象的fetchone/fetchall方法得到返回的行信息。
详细介绍这两种方法如何获取返回值:

  1. fetchone()获取行信息,每次得到一行的元组返回值。 如果没有元组了,返回None值。例如,
    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
  2. 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

Step3–关闭连接

cursor.close ()
conn.commit ()–注释:如果是MyISAM表,commit就不起作用,因为它是非事务存储引擎,如果是InnoDB就作用噢conn.close ()

最后附上参考文档中的例子一枚:

#!/usr/bin/python
# animal.py – create animal table and
# retrieve information from it

import sys
import MySQLdb

# connect to the MySQL server
try:
conn = MySQLdb.connect (host = “localhost”,user = “testuser”,passwd = “testpass”,db = “test”)
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(40),
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

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 ()
cursor = conn.cursor (MySQLdb.cursors.DictCursor)
cursor.execute (“SELECT name, category FROM animal”)
result_set = cursor.fetchall ()
for row in result_set:
print “%s, %s” % (row[“name”], row[“category”])
print “Number of rows returned: %d” % cursor.rowcount

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

conn.commit ()
conn.close ()

 

2 thoughts on “Python连接MySQL操作”

  1. Python很强大啊,准备以后好好学学,还有shell还有perl等等云云,你在什么下面用的mysql啊?

  2. Python看样子是有用的东东啊

    话说,最近貌似也要搞搞mysql了,不过是下的图形化窗口

Leave a Reply

Your email address will not be published. Required fields are marked *