---
title: "Python Database学习"
author: "yangsq"
date: "2007-11-13T17:54:00Z"
tags: []
slug: "python-database"
draft: false
lastmod: "2007-11-13T17:54:00Z"
id: 139345
url: "https://yangsq.iteye.com/blog/139345"
---

进行程序设计，很容易用到数据库。最近实验室课题要处理大量的文本数据，于是想到了python，顺便学习一下python的数据库编程。这里只是针对mysql（5.0）和sqlserver（2005）的连接性学习，至于深入的学习，以后再看DBAPI吧。

- Mysql connection test

      和java要下mysql connection driver一样，python也得下driver才能用，python的mysql driver 叫做MySQLdb，我在sourceForge上下了一个MySQL-python-1.2.2.win32-py2.5.exe。下好后直接安装就行，可能过程中会选择一下python的安装路径。超简单，下面是[http://www.devshed.com/](http://www.devshed.com/)上copy的一个例子，如下：

python 代码

01. # import mysql module
02. import MySQLdb
03. # create a connection
04. db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')
05. # create a cursor
06. cursor = db.cursor()
07. # execute sql statement
08. cursor.execute('select * from node')
09. # get result set
10. # fetchall() return a tuple that contains results as tuples
11. # inner tuple represent a row of the result set
12. result = cursor.fetchall()
13. for record in result:
14. print record
15. # close the connection
16. db.close()

输出结果是：（test是我建的一个测试表，字段有id（主键）、name、gender）

sql 代码

 

01. &gt;&gt;&gt;
02. (1L, 'Jeff', 'M')
03. (2L, 'Ed', 'F')
04. (3L, 'Christiaan', 'F')
05. (4L, 'yangsq', 'M')
06. (5L, 'Adam', 'M')
07. (6L, 'Cynthia', 'M')
08. (7L, 'Joylette', 'F')
09. (8L, 'Amanda', 'M')
10. (9L, 'Nathaniel', 'M')
11. (10L, 'Bryan', 'M')

 

- SqlServer connection test

         同样，下driver先，还是sourceForge，名字叫pymssql，我下的是pymssql-0.8.0.win32-py2.5.exe，安装和mysql的一样。下面是链接测试代码：

python 代码

1. import pymssql
2. con = pymssql.connect(host='59.64.159.50', user='sa', password='admin233', database='test')
3. cur = con.cursor()
4. query = 'select top 100 * from demo'
5. cur.execute(query)
6. result = cur.fetchall()
7. for record in result:
8. print record
9. con.close()

上面的代码看起来和mysql的没啥区别，结果就不帖了。

至于其他数据库，还没用到，先不学了。python还提供了更多关于数据库方面的支持，以后再说吧。