ITeye博客

Python Database学习

yangsq · 2007-11-13 17:54 · python学习 · Markdown

进行程序设计,很容易用到数据库。最近实验室课题要处理大量的文本数据,于是想到了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 代码

  1. # import mysql module
  2. import MySQLdb
  3. # create a connection
  4. db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')
  5. # create a cursor
  6. cursor = db.cursor()
  7. # execute sql statement
  8. cursor.execute('select * from node')
  9. # 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 代码

 

  1. >>>
  2. (1L, 'Jeff', 'M')
  3. (2L, 'Ed', 'F')
  4. (3L, 'Christiaan', 'F')
  5. (4L, 'yangsq', 'M')
  6. (5L, 'Adam', 'M')
  7. (6L, 'Cynthia', 'M')
  8. (7L, 'Joylette', 'F')
  9. (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还提供了更多关于数据库方面的支持,以后再说吧。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。