Python資料庫操作手冊

來源:互聯網
上載者:User
資料|資料庫 資料庫的操作在現在的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

回本欄首頁


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.