pyodbc的簡單使用

1、連接數據庫


1)直接連接數據庫和創建一個遊標(cursor)

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
cursor = cnxn.cursor()

2)使用DSN連接。通常DSN連接並不需要密碼,還是需要提供一個PSW的關鍵字。

cnxn = pyodbc.connect('DSN=test;PWD=password')

cursor = cnxn.cursor()

關於連接函數還有更多的選項,可以在pyodbc文檔中的 connect funtion 和 ConnectionStrings查看更多的細節

2、數據查詢(SQL語句爲 select ...from..where)

1)所有的SQL語句都用cursor.execute函數運行。如果語句返回行,比如一個查詢語句返回的行,你可以通過遊標的fetch函數來獲取數據,這些函數有(fetchone,fetchall,fetchmany).如果返回空行,fetchone函數將返回None,而fetchall和fetchmany將返回一個空列。

cursor.execute("select user_id, user_name from users")

row = cursor.fetchone()

if row:

print row

2)Row這個類,類似於一個元組,但是他們也可以通過字段名進行訪問。

cursor.execute("select user_id, user_name from users")
row = cursor.fetchone()
print 'name:', row[1]          # access by column index
print 'name:', row.user_name   # or access by name


3)如果所有的行都被檢索完,那麼fetchone將返回None.

while 1:

row = cursor.fetchone()

if not row:

break

print 'id:', row.user_id

4)使用fetchall函數時,將返回所有剩下的行,如果是空行,那麼將返回一個空列。(如果有很多行,這樣做的話將會佔用很多內存。未讀取的行將會被壓縮存放在數據庫引擎中,然後由數據庫服務器分批發送。一次只讀取你需要的行,將會大大節省內存空間)

cursor.execute("select user_id, user_name from users")

rows = cursor.fetchall()

for row in rows:

print row.user_id, row.user_name

5)如果你打算一次讀完所有數據,那麼你可以使用cursor本身。

cursor.execute("select user_id, user_name from users"):

for row in cursor:

print row.user_id, row.user_name

6)由於cursor.execute返回一個cursor,所以你可以把上面的語句簡化成:

for row in cursor.execute("select user_id, user_name from users"):

print row.user_id, row.user_name


7)有很多SQL語句用單行來寫並不是很方便,所以你也可以使用三引號的字符串來寫:

cursor.execute("""

select user_id, user_name

from users

where last_logon < '2001-01-01'

and bill_overdue = 'y'

""")


3、參數

1)ODBC支持在SQL語句中使用一個問號來作爲參數。你可以在SQL語句後面加上值,用來傳遞給SQL語句中的問號。

cursor.execute("""

select user_id, user_name

from users

where last_logon < ?

and bill_overdue = ?

""", '2001-01-01', 'y')


這樣做比直接把值寫在SQL語句中更加安全,這是因爲每個參數傳遞給數據庫都是單獨進行的。如果你使用不同的參數而運行同樣的SQL語句,這樣做也更加效率。

3)python DB API明確說明多參數時可以使用一個序列來傳遞。pyodbc同樣支持:

cursor.execute("""

select user_id, user_name

from users

where last_logon < ?

and bill_overdue = ?

""", ['2001-01-01', 'y'])

cursor.execute("select count(*) as user_count from users where age > ?", 21)

row = cursor.fetchone()

print '%d users' % row.user_count


4、數據插入

1)數據插入,把SQL插入語句傳遞給cursor的execute函數,可以伴隨任何需要的參數。

cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")

cnxn.commit()

cursor.execute("insert into products(id, name) values (?, ?)", 'pyodbc', 'awesome library')

cnxn.commit()

注意調用cnxn.commit()函數:你必須調用commit函數,否者你對數據庫的所有操作將會失效!當斷開連接時,所有懸掛的修改將會被重置。這很容易導致出錯,所以你必須記得調用commit函數。

5、數據修改和刪除

1)數據修改和刪除也是跟上面的操作一樣,把SQL語句傳遞給execute函數。但是我們常常想知道數據修改和刪除時,到底影響了多少條記錄,這個時候你可以使用cursor.rowcount的返回值。

cursor.execute("delete from products where id <> ?", 'pyodbc')

print cursor.rowcount, 'products deleted'

cnxn.commit()


2)由於execute函數總是返回cursor,所以有時候你也可以看到像這樣的語句:(注意rowcount放在最後面)

deleted = cursor.execute("delete from products where id <> 'pyodbc'").rowcount

cnxn.commit()


同樣要注意調用cnxn.commit()函數

6、小竅門

1)由於使用單引號的SQL語句是有效的,那麼雙引號也同樣是有效的:

deleted = cursor.execute("delete from products where id <> 'pyodbc'").rowcount

2)假如你使用的是三引號,那麼你也可以這樣使用:

deleted = cursor.execute("""

delete

from products

where id <> 'pyodbc'

""").rowcount


3)有些數據庫(比如SQL Server)在計數時並沒有產生列名,這種情況下,你想訪問數據就必須使用下標。當然你也可以使用“as”關鍵字來取個列名(下面SQL語句的“as name-count”)

row = cursor.execute("select count(*) as user_count from users").fetchone()

print '%s users' % row.user_count


4)假如你只是需要一個值,那麼你可以在同一個行局中使用fetch函數來獲取行和第一個列的所有數據。

count = cursor.execute("select count(*) from users").fetchone()[0]

print '%s users' % count


如果列爲空,將會導致該語句不能運行。fetchone()函數返回None,而你將會獲取一個錯誤:NoneType不支持下標。如果有一個默認值,你能常常使用ISNULL,或者在SQL數據庫直接合並NULLs來覆蓋掉默認值。


maxid = cursor.execute("select coalesce(max(id), 0) from users").fetchone()[0]在這個例子裏面,如果max(id)返回NULL,coalesce(max(id),0)將導致查詢的值爲0。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章