分类: C/C++
2008-04-23 22:03:40
Python 的数据库操作
作者:JerryZ
数据库的操作在目前的 Python 里面已经变得十分的好用,因为有了一套 API 标准。本文下面就讲讲如何使用这套API。它包括以下部分:
一、
connect( parameters... )
其中的参数格式如下:
dsn 数据源名称 user 用户名(可选) password 密码(可选) host 主机名(可选) database 数据库名(可选)
举个例子:
connect(dsn=''myhost:MYDB'',user=''guido'',password=''234$'')
或者
connect(''218.244.20.22'',''username'',''password'',''databasename'')
此标准规定了以下的一些全局变量,
apilevel:
表示 DB-API 的版本,分 1.0 和 2.0 。如果没有定义,则默认为 1.0。
threadsafety:
0 Threads may not share the module.
1 Threads may share the module, but not connections.
2 Threads may share the module and connections.
3 Threads may share the module, connections and cursors.
paramstyle:
用于表示参数的传递方法,分为以下五种:
''qmark'' 问号标识风格. e.g ''... WHERE name=?''
''numeric'' 数字,占位符风格. e.g ''... WHERE name=:1''
''named'' 命名风格. e.g ''WHERE name=:name''
''format'' ANSI C printf风格. e.g ''... WHERE name=%s''
''pyformat'' Python扩展表示法. e.g ''... WHERE name=%(name)s''
异常类:
StandardError |__Warning |__Error |__InterfaceError |__DatabaseError |__DataError |__OperationalError |__IntegerityError |__InternalError |__ProgrammingError |__NotSupportedError
五、
下面举的例子是以MSSQL为样板的,但是换成其他的驱动也一样可以做,这个就和 Perl
的数据库操作十分的类似,可以让我们很方便的实现不同数据库之间的移植工作。
1、查询数据
import MSSQL db = MSSQL.connect(''SQL Server IP'', ''username'', ''password'', ''db_name'') c = db.cursor() sql = ''select top 20 rtrim(ip), rtrim(dns) from detail'' c.execute(sql) for f in c.fetchall(): print "ip is %s, dns is %s" % (f[0], f[1])
2、插入数据
sql = ''insert into detail values(''192.168.0.1'', '''') c.execute(sql)
3、ODBC的一个例子
import dbi, odbc # ODBC modules import time # standard time module dbc = odbc.odbc( # open a database connection ''sample/monty/spam'' # ''datasource/user/password'' ) crsr = dbc.cursor() # create a cursor crsr.execute( # execute some SQL """ SELECT country_id, name, insert_change_date FROM country ORDER BY name """ ) print ''Column descriptions:'' # show column descriptions for col in crsr.description: print '' '', col result = crsr.fetchall() # fetch the results all at once print ''\nFirst result row:\n '', result[0] # show first result row print ''\nDate conversions:'' # play with dbiDate object date = result[0][-1] fmt = '' %-25s%-20s'' print fmt % (''standard string:'', str(date)) print fmt % (''seconds since epoch:'', float(date)) timeTuple = time.localtime(date) print fmt % (''time tuple:'', timeTuple) print fmt % (''user defined:'', time.strftime(''%d %B %Y'', timeTuple)) -------------------------------output-------------------------------- Column descriptions: (''country_id'', ''NUMBER'', 12, 10, 10, 0, 0) (''name'', ''STRING'', 45, 45, 0, 0, 0) (''insert_change_date'', ''DATE'', 19, 19, 0, 0, 1) First result row: (24L, ''ARGENTINA'',) Date conversions: standard string: Fri Dec 19 01:51:53 1997 seconds since epoch: 882517913.0 time tuple: (1997, 12, 19, 1, 51, 53, 4, 353, 0) user defined: 19 December 1997