數據庫的操作在現在的python里面已經變得十分的好用,有了一套api標準.下面的就是講講如何的去使用這套框架定義.此框架包含以下部分模塊接口 連接對象 游標對象 dbi輔助對象 數據類型與定義 如何實現的提示 從1.0到2.0的變化 例子 模塊接口
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
連接對象
連接對象包含如下方法:
.close() 關閉連接 .commit() 用于事務處理里面的提交操作 .rollback() 用于事務處理里面的回滾操作 .cursor() 獲得一個游標 游標對象
游標對象包含如下屬性和方法:
.description 一個列表(name,type_code,display_size,internal_size,precision,scale,null_ok) 此屬性只有在取得了數據之后才有,不然會是null值 .rowcount 表示返回值的行數.如果沒有執行executexxx()方法或者此模塊沒有實現這個方法,就會返回-1 .callproc(procname[,parameters]) (此為可選方法,應為不是所有的數據庫都支持存儲過程的) .close() 關閉游標 .execute(operation[,parameters]) 準備并執行一個數據庫操作(包括查詢和命令) .executemany(operation,seq_of_parameters) 準備一個數據庫命令,然后根據參數執行多次命令 .fetchone() 返回第一行的查詢結果 .fetchmany([size=cursor.arraysize]) 返回指定個多個行的值 .fetchall() 返回所有的查詢結果 .arraysize 這個參數值表示fetchmany默認情況之下獲取的行數 數據類型與定義定義一些常用的數據類型.但是目前用不到,就先不分析備注
當然,我們要知道的是,這個只是一個標準,一般來說標準里面定義了的會實現,但還有很多特定的實現,我們也需要去掌握哪些東西,不過如果我們將這些標準的掌握了,那么操作一般的就不會有問題了.
下面給出幾個數據庫相關的網址
database topic guide python的數據庫使用向導,有相當不錯的資料,包括api定義,驅動聯結等等 mssql 驅動 就是mssql的驅動程序 例子
下面舉的例子是以mssql為樣板的,但是換成其他的驅動也一樣可以做,這個就和perl的數據庫操作十分的類似,可以讓我們很方便的實現不同數據庫之間的移植工作.
1. 查詢數據
import mssqldb = 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', 'www.dns.com.cn')c.execute(sql)
3. odbc的一個例子
import dbi, odbc # odbc modulesimport time # standard time moduledbc = odbc.odbc( # open a database connection 'sample/monty/spam' # 'datasource/user/password' )crsr = dbc.cursor() # create a cursorcrsr.execute( # execute some sql """ select country_id, name, insert_change_date from country order by name """ )print 'column descriptions:' # show column descriptionsfor col in crsr.description: print ' ', colresult = crsr.fetchall() # fetch the results all at onceprint '/nfirst result row:/n ', result[0] # show first result rowprint '/ndate conversions:' # play with dbidate objectdate = 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', <dbidate object at 7f1c80>)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
回本欄首頁