Python 中的 MySQLdb 連線


Mysql是最廣泛使用的開源資料庫之一。Python提供連線到此資料庫的方法,並使用該資料庫儲存和檢索資料。

安裝 pymysql

根據使用的 Python 環境,pymysql 軟體包可以透過以下方法之一進行安裝。

# From python console
pip install pymysql
#Using Anaconda
conda install -c anaconda pymysql
# Add modules using any python IDE
pymysql

連線到 MySQL

現在,我們可以使用以下程式碼連線到 MySQL 環境。連線後,我們將找出資料庫的版本。

示例

import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)

# disconnect from server
db.close()

輸出

執行以上程式碼得到以下結果:

Database version : 8.0.19

執行資料庫命令

為了執行資料庫命令,我們建立了一個數據庫遊標和一個 SQL 查詢以傳遞到該遊標中。然後,我們使用遊標的 execute 方法來從遊標執行中獲取結果。

示例

import pymysql
# Open database connection
db = pymysql.connect("localhost","username","paswd","DBname" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
      WHERE INCOME > '%d'" % (1000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # Now print fetched result
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
            (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"
# disconnect from server
db.close()

輸出

執行以上程式碼得到以下結果:

fname = Jack, lname = Ma, age = 31, sex = M, income = 12000

更新日期:2020 年 2 月 4 日

249 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告