python操作sql server數據庫


pyodbc庫

可用於SQL Server數據庫的連接,但除此之外,還可用於Oracle,Excel, MySql等,安裝Anaconda時默認已安裝。

安裝:pip install pyodbc

1、連接數據庫

1)直接連接數據庫和創建一個游標(cursor)(使用過)

coxn=pyodbc.connect(driver="ODBC Driver 13 for SQL Server",server="localhost",user="sa",password="fooww123,",database="testdb")#連接數據庫
cursor=coxn.cursor()#獲取游標對象

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

 cnxn =pyodbc.connect('DSN=test;PWD=password')
 cursor =cnxn.cursor()
2、操作數據庫
所有的SQL語句都用cursor.execute函數運行。
1)查詢操作,fetchone獲取一行數據
 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()
  ifnot 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.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
 cnxn.commit()
注意調用 cnxn.commit()函數:你必須調用 commit函數,否者你對數據庫的所有操作將會失效!當斷開連接時,所有懸掛的修改將會被重置。這很容易導致出錯,所以你必須記得調用 commit函數。
6)數據修改和刪除

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

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

  printcursor.rowcount, 'products deleted'
  cnxn.commit()

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

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

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

import  pyodbc
#封裝的一個簡單的demo class MsSql: def __init__(self,driver,server,user,pwd,db): self.driver=driver self.server=server self.user=user self.pwd=pwd self.db=db def __get_connect(self): if not self.db: raise (NameError,"沒有設置數據庫信息") self.conn=pyodbc.connect(driver=self.driver,server=self.server,user=self.user,password=self.pwd,database=self.db)#連接數據庫 cursor=self.conn.cursor()#使用cursor()方法創建游標對象 if not cursor: raise (NameError,"連接數據庫失敗") else: return cursor def exec_query(self,sql): '''執行查詢語句''' cursor=self.__get_connect() cursor.execute(sql) res_list=cursor.fetchall()#使用fetchall()獲取全部數據 self.conn.close()#查詢完畢關閉連接 return res_list def exec_not_query(self,sql): '''執行非查詢語句''' cursor=self.__get_connect() cursor.execute(sql) self.conn.commit() self.conn.close() if __name__ == '__main__': ms=MsSql(driver="ODBC Driver 13 for SQL Server",server="localhost",user="sa",pwd="fooww123,",db="testdb") result=ms.exec_query("select id,name from webuser") for i in result: print(i) newsql = "update webuser set name='%s' where id=1" % u'aa' # print(newsql) ms.exec_not_query(newsql)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM