七月 30th, 2010 @ 2:27 下午 

安装MySQLdb模块:

MySQLdb模块下载地址:http://sourceforge.net/projects/mysql-python/

安装过程:

1
2
$python setup.py build
$python setup.py install

使用方法:

提取自:Writing MySQL Scripts with Python DB-API
原文地址:http://www.kitebird.com/articles/pydbapi.html
作者:Paul DuBois

一个很小的Demon用来查询Mysql的版本号:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import MySQLdb   #引入模块
#首先连接数据库
conn = MySQLdb.connect (host = "localhost",
                        user = "testuser",
                        passwd = "testpass",
                        db = "test",
                        port = 3307)
# 若端口号是默认的3306端口,可以省略。
# PS:python的一个特点如果传入参数带参数名时,可以更改传参顺序,比如上面的参数顺序就可以重新排序lol

cursor = conn.cursor ()   #获得该连接的一个指针
cursor.execute ("SELECT VERSION()")   #通过指针执行SQL语句
row = cursor.fetchone ()   #用fetchone()函数获得返回内容
print "server version:", row[0]   #输出内容
cursor.close ()   #关闭指针
conn.close ()   #操作最后关闭连接

接下来的例子使用了更多方便的用法,写成了python脚本,可以作为脚本文件执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/python
#coding:utf8
# animal.py - create animal table and
# retrieve information from it

import sys
import MySQLdb

# 链接数据库

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)

# 创建animal表并添加数据

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 "添加数据的行数: %d" % cursor.rowcount

# 用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 "取得数据的行数: %d" % cursor.rowcount

# 用fetchall()函数提取全部数据

  cursor.execute ("SELECT name, category FROM animal")
  rows = cursor.fetchall ()
  for row in rows:
    print "%s, %s" % (row[0], row[1])
  print "取得数据的行数: %d" % cursor.rowcount

# 将name字段值为turtle的数据的name值改snake,
# 然后通过换位符将其改回原样

  cursor.execute ("""
        UPDATE animal SET name = 'turtle'
        WHERE name = 'snake'
      """
)
  print "更新数据行数: %d" % cursor.rowcount
  cursor.execute ("""
        UPDATE animal SET name = %s
        WHERE name = %s
      """
, ("snake", "turtle"))
  print "更新数据行数: %d" % cursor.rowcount

# 通过创建一个dict指针来接受带有字段名信息的字段值,这样就不用
# 通过字段的对应位置来取值

  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 "取得数据的行数: %d" % cursor.rowcount

  cursor.close ()

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

# connection对象的commit()方法提交所有当前未完成的改变,使数据库永久的记录下来。
# 在DB-API中,连接时,自动提交模式(autocommit mode)是禁用的,所以必须调用commit()提交数据,否则更改可能会丢失。
conn.commit ()
conn.close ()

注:第二段源码翻译的过程中,我在第二行添加了#coding:utf8,这样python才能支持中文。

作者: Sunny
原创文章: 转载请注明出自 Sunny Way.
最后编辑: 七月 30th, 2010 @ 06:41 下午
Email永久链接
Tags
标签: , ,
分类: MySQL, Python


 

这篇日志的回复 » (没有回复)

 
发表回复

提示: 您可以使用以下标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags
Comment Meta:
回复RSS
引用URI


 最近 50 篇日志
 后退
切换主题...
  • 访问 » 8663
  • 日志 » 59
  • 回复 » 77
切换主题...
  • VoidVoid
  • LifeLife
  • EarthEarth
  • WindWind « Default
  • WaterWater
  • FireFire
  • LightLight

留言板



    No Child Pages.