@

前言

相信很多小夥伴在使用python進行自動化測試的時候,都會涉及到資料庫資料校驗的問題,在前面的隨筆中就已經有講過連線mysql的使用,今天給大家彙總一下python對接幾大常用的資料庫操作的方法!眾所周知,python有著極其豐富的第三方庫,所以不管你使用的是關係型資料庫(oracle,mysql, sqlserver等),還是非關係型資料庫(redis,mongoDB),python都有與之對應的第三方庫。下面給大家一一介紹。

常見資料庫

Python 標準資料庫介面為 Python DB-API,Python DB-API為開發人員提供了資料庫應用程式設計介面。

Python 資料庫介面支援非常多的資料庫,你可以選擇適合你專案的資料庫:

GadFly

mSQL

MySQL

PostgreSQL

Microsoft SQL Server 2000

Informix

Interbase

Oracle

Sybase

Mysql

  • MySQL是一個關係型資料庫,MySQL由於效能高、成本低、可靠性好,已經成為最流行的開源資料庫。最開始由瑞典的MySQL AB公司開發,後來被甲骨文公司(Oracle)收購。
  • 安裝_1:pip install mysql
  • 安裝_2:pip install PyMySQL

# -*- coding: utf-8 -*-
# @Author : 一凡 import MySQLdb # 開啟資料庫連線
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' ) # 使用cursor()方法獲取操作遊標
cursor = db.cursor() # 使用execute方法執行SQL語句
cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法獲取一條資料
data = cursor.fetchone() print "Database version : %s " % data # 關閉資料庫連線
db.close()

Oracle

  • python 對接 Oracle 資料庫,使用的第三方庫為 cx_Oracle
  • 安裝: pip install cx_Oracle
# -*- coding: utf-8 -*-
# @Author : 一凡 import cx_Oracle # 第一步 連線資料庫, 引數為'賬號/密碼/@ip:埠/庫名'
con = cx_Oracle.connect('user_name/[email protected]::8080/databases')
# 第二步 建立遊標
cur = con.cursor()
# 第三步 執行sql語句
sql = 'SELECT * FROM user;'
cur.execute(sql)

sql-server

  • python 對接 sql-server資料庫,使用的第三方庫為 pymssql 。
  • 安裝: pip install pymssql

# -*- coding: utf-8 -*-
# @Author : 一凡 import pymssql # 第一步 連線到資料庫
con = pymssql.connect(host='xxx', # 資料庫的地址
user='xxx', # 登入資料庫的賬號
password='xxxx', # 登入資料庫的密碼
database='xxx') # 庫名
# 第二步 建立遊標
cur = con.cursor()
# 第三步 執行sql語句
sql = 'SELECT * FROM user;'
cur.execute(sql)

PostgreSQL

  • python 對接 PostgreSQL資料庫,使用的第三方庫為 psycopg2 。
  • 安裝: pip install psycopg2

# -*- coding: utf-8 -*-
# @Author : 一凡 import psycopg2 # 第一步 連線到資料庫
con = psycopg2.connect(database="xxxxx", # 庫名
user="xxxxx", # 資料庫賬號
password="xxxxxx", # 資料庫密碼
host="xxxxxx", # 資料庫地址
port="5432") # 資料庫埠號
# 第二步 建立遊標
cur = con.cursor()
# 第三步 執行sql語句
sql = 'SELECT * FROM user;'
cur.execute(sql)

MongoDB

  • python 對接MongoDB資料庫,使用的第三方庫為 pymongo 。
  • 安裝: pip install pymongo
# -*- coding: utf-8 -*-
# @Author : 一凡 import pymongo # 第一步:建立連線,資料庫地址,埠號
client = pymongo.MongoClient("localhost", 27017)
# 第二步:選取資料庫
db = client.test1
# 第三步:選取集合
stu = db.stu # 第四步:執行相關操作
# 新增一條資料
data1 = {name:'test',age:18}
stu.insert_one(data1)
# 獲取一條資料
res = stu.find_one()

Redis

  • python 對接Redis資料庫,使用的第三方庫為 redis 。
  • 安裝: pip install redis

# -*- coding: utf-8 -*-
# @Author : 一凡 import redis # 連線資料庫
st = redis.StrictRedis(
host='localhost', # 資料庫地址
port='6379', # 埠:
db='testdata', # 庫名:
)
# redis操作的命令,對應st物件的方法
# 比如在資料庫中建立一條鍵為test的資料,往裡面新增3個元素
st.lpush('test',11,22,33)

如果想學習交流,就快加入:893694563,群內學軟體測試,分享技術和學習資料,陪你一起成長和學習。那就:碼上開始