python:數據庫連接操作入門


模塊

1 import pymssql,pyodbc

 

模塊說明

  pymssql和pyodbc模塊都是常用的用於SQL Server、MySQL等數據庫的連接及操作的模塊,當然一些其他的模塊也可以進行相應的操作,類似adodbapi、mssql、mxODBC等,我們在實際用的時候選擇其中一個模塊就好,對於每一個模塊都有相應的支持版本和支持平台,大家可以自行查閱文檔https://wiki.python.org/moin/SQL%20Server

 

模塊安裝 

1 pip install pymssql

  關於pip的使用我在我的另一篇博客里提到了https://www.cnblogs.com/jyroy/p/9410593.html

 

模塊使用

  我們利用python來進行數據庫的操作,那么第一步就應該是連接數據庫,這里我們用pymssql模塊中的connect方法連連接,在pyodbc模塊中同樣也是利用connect方法。

  • 使用connect創建連接對象
  • connect.cursor創建游標對象,SQL語句的執行基本都在游標上進行
  • cursor.executeXXX方法執行SQL語句,cursor.fetchXXX獲取查詢結果等
  • 調用close方法關閉游標cursor和數據庫連接

 

  pymssql模塊連接

   '''
    pymssql模塊連接SQL Server數據庫
    '''

    import pymssql   

     '''格式1'''
    host= "XXXXXXXXXXXX"  # 數據庫服務器名稱或IP
    user = "test"
    password = "123"
    database = "test"

    conn = pymssql.connect(host, user, password, database)

    '''格式2'''
    conn = pymssql.connect(host='XXXXXXXXXXXX', user="test", password="123", database="test")

 

  pyodbc模塊連接

    import pyodbc

    conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=test;DATABASE=test;UID=user;PWD=password')

  不同的SQL server版本對應的DRIVER字段不同。對應關系如下:

  • {SQL Server} - released with SQL Server 2000
  • {SQL Native Client} - released with SQL Server 2005 (also known as version 9.0)
  • {SQL Server Native Client 10.0} - released with SQL Server 2008
  • {SQL Server Native Client 11.0} - released with SQL Server 2012

  使用pyodbc需要安裝微軟官方的Native Client(沒有安裝會報錯IM002),安裝SQL server management studio會自動附帶安裝(控制面板里可以看到安裝的版本)。如果沒有安裝過需要在https://msdn.microsoft.com/en-us/data/ff658533.aspx下載安裝(sqlncli.msi)。建議選擇與遠程數據庫版本相對應的Native Client。如果本地安裝的Native Client是高版本,則DRIVER={SQL Server Native Client 11.0}需要填寫的是本地的高版本。

 

獲取數據庫內容

 

  這里涉及到游標的使用(游標大家有不理解的可以參考一下這個大佬的博客https://www.cnblogs.com/selene/p/4480328.html

1     '''
2     游標的使用
3     '''
4     cursor_1 = conn.cursor()     #獲取游標
5 
6     cursor_1.execute("select Sno from student")    #執行語句
7 
8     print (cursor_1.fetchone())              #結果是元組,fetchone()獲取查詢結果
9  

  

  fetchone() :返回單個的元組,也就是一條記錄(row),如果沒有結果 則返回 None

  fetchall() :返回多個元組,即返回多個記錄(rows),如果沒有結果 則返回 ()

 1     '''
 2     fetchall()的使用
 3     '''
 4     cursor_2 = conn.cursor()
 5 
 6     cursor_2.execute("select Sno, Sname from students")
 7 
 8     rows = cursor_2.fetchall()
 9 
10     for row in rows:
11         print(row.Sno, row.Sname)

  

  由於execute返回的是cursor本身,所以如果你需要一次直接獲取所有內容可以直接使用cursor本身來獲取

1 cursor.execute("select Sno, Sname from students"):
2 
3 for row in cursor:
4     print(row.Sno, row.Sname )

  

  關於游標這里還存在一個要向大家專門說明的地方,

  就是一個連接一次只能有一個游標的查詢處於活躍狀態,具體什么意思大家可以看下面的代碼。

1     cursor_1 = conn.cursor()     #獲取游標
2     cursor_1.execute("select Sno from student")    #執行語句
3 
4     cursor_2 = conn.cursor()
5     cursor_2.execute("select * from student where Sno=1")
6 
7     print (cursor_1.fetchall())             #顯示的是cursor_2的查詢結果
8     print (cursor_2.fetchall())             #不顯示任何結果

  提供一個解決的辦法

 1      '''解決上述問題'''
 2 
 3     cursor_1.execute("select Sno from student")
 4     cursor_list_1 = cursor_1.fetchall()   #用list把結果存儲下來
 5 
 6     cursor_2.execute("select * from student where Sno=1")
 7     cursor_list_2 = cursor_2.fetchall()
 8 
 9     print (cursor_list_1)               #通過print list來獲取cursor_1的結果
10     print (cursor_list_2)    

 

   在游標的正常使用中游標獲取的查詢結果,一行為一個元組。

  我們在實際使用中可以根據需求,用 as_dict 方法返回一個字典變量,其中字典的Key為數據表的列名

 1     '''游標返回行為字典變量'''
 2 
 3     cursor_3 = conn.cursor(as_dict=True)      #創建游標時指定as_dict參數來使游標返回字典變量
 4     cursor_3.execute("select * from student")
 5 
 6     for row in cursor_3:
 7         print('ID=%d' % row['Sno'])    #鍵名為列表的列名  {Sno:ID}
 8     
 9     print (cursor_3.fetchone())
10     
11     conn.close()     #調用close方法關閉游標cursor和數據庫連接

 

  大家如果覺得上面的代碼寫起來看上去太長,給大家提供一個代碼量小的數據庫操作解決辦法

  就是 with語句,即上下文管理器,它的好處一個是代碼的集成度高,一個是省去顯示的調用close方法關閉連接和游標

 1     '''
 2     使用with語句(上下文管理器)
 3     '''
 4 
 5     '''通過使用with語句來省去顯示的調用close方法關閉連接和游標'''
 6     with pymssql.connect(host='LAPTOP-3OTJHAG9', user="sa", password="123", database="TEST") as conn:    
 7 
 8     #相當於 conn = pymssql.connect(host='XXXXXXXXXXXX', user="test", password="123", database="test")
 9 
10         with conn.cursor(as_dict=True) as cursor_4:
11             cursor_4.execute('select * from student')
12             for row in cursor_4:
13                 print ('ID=%d' %(row['Sno']))

 

  

關於數據庫的增刪改

 

  增刪改數據庫的內容也是直接傳遞SQL語句給execute方法。但要注意運行之后需要用commit提交變更

1 cursor.execute("insert into students(id, name) values ('123', 'My name')")
2 conn.commit()    
3 cursor.execute("delete from studnts where id=‘123’")

4 conn.commit()

 


 

關於pymssql模塊,還有不明白的大家可以看下官網http://www.pymssql.org/

 


免責聲明!

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



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