进行程序设计,很容易用到数据库。最近实验室课题要处理大量的文本数据,于是想到了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/上copy的一个例子,如下:
python 代码
- # import mysql module
- import MySQLdb
- # create a connection
- db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')
- # create a cursor
- cursor = db.cursor()
- # execute sql statement
- cursor.execute('select * from node')
- # get result set
- # fetchall() return a tuple that contains results as tuples
- # inner tuple represent a row of the result set
- result = cursor.fetchall()
- for record in result:
- print record
- # close the connection
- db.close()
输出结果是:(test是我建的一个测试表,字段有id(主键)、name、gender)
sql 代码
- >>>
- (1L, 'Jeff', 'M')
- (2L, 'Ed', 'F')
- (3L, 'Christiaan', 'F')
- (4L, 'yangsq', 'M')
- (5L, 'Adam', 'M')
- (6L, 'Cynthia', 'M')
- (7L, 'Joylette', 'F')
- (8L, 'Amanda', 'M')
- (9L, 'Nathaniel', 'M')
- (10L, 'Bryan', 'M')
- SqlServer connection test
同样,下driver先,还是sourceForge,名字叫pymssql,我下的是pymssql-0.8.0.win32-py2.5.exe,安装和mysql的一样。下面是链接测试代码:
python 代码
- import pymssql
- con = pymssql.connect(host='59.64.159.50', user='sa', password='admin233', database='test')
- cur = con.cursor()
- query = 'select top 100 * from demo'
- cur.execute(query)
- result = cur.fetchall()
- for record in result:
- print record
- con.close()
上面的代码看起来和mysql的没啥区别,结果就不帖了。
至于其他数据库,还没用到,先不学了。python还提供了更多关于数据库方面的支持,以后再说吧。