說(shuō)明:
在實(shí)際工作中,我們經(jīng)常要使用Python對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作(增刪改查)。不同的數(shù)據(jù)庫(kù)我們需要下載不同的使用模塊,例如我們需要訪問(wèn)Oracle數(shù)據(jù)庫(kù)和Mysql數(shù)據(jù),你需要下載Oracle和MySQL數(shù)據(jù)庫(kù)模塊。
Python 標(biāo)準(zhǔn)數(shù)據(jù)庫(kù)接口為 Python DB-API,Python 數(shù)據(jù)庫(kù)接口支持非常多的數(shù)據(jù)庫(kù),你可以選擇適合你項(xiàng)目的數(shù)據(jù)庫(kù)。詳細(xì)可以訪問(wèn)官方文檔查看相關(guān)信息。
https://wiki.python.org/moin/DatabaseInterfaces
本次介紹主流數(shù)據(jù)庫(kù)的連接:Oracle、Sql Server、Mysql
1、Oracle數(shù)據(jù)庫(kù)
這里使用的是cx_Oracle模塊來(lái)操作Oracle數(shù)據(jù)庫(kù)
#Oracle
importcx_Oracle
host ='192.168.1.1'
port ='1521'
dbname ='testdb'
username ='test'
password ='test'
dsn = cx_Oracle.makedsn(host, port, dbname)
connection = cx_Oracle.connect(username, password, dsn)
# 使用cursor()方法獲取操作游標(biāo)
cursor = connection.cursor()
# SQL 查詢語(yǔ)句
sql ='select*from testtable'
# 執(zhí)行SQL語(yǔ)句
cursor.execute(sql)
# 獲取一條記錄
# fetchall可以獲取所有記錄列表
res = cursor.fetchone()
print(res)
# 關(guān)閉數(shù)據(jù)庫(kù)連接
connection.close()
2、Sql Server數(shù)據(jù)庫(kù)
這里使用的是pyodbc模塊來(lái)操作Sql Server數(shù)據(jù)庫(kù)
#Sql Server
importpyodbc
host ='192.168.1.1'
username ='sa'
password ='test'
dbname ='testdb'
conn_infomssql ='DRIVER=;DATABASE=%s;
SERVER=%s;UID=%s;PWD=%s'% (dbname, host, username, password)
conn = pyodbc.connect(conn_infomssql)
# 使用cursor()方法獲取操作游標(biāo)
cursor = conn.cursor()
# SQL 查詢語(yǔ)句
sql ='select*from testtable'
# 執(zhí)行SQL語(yǔ)句
cursor.execute(sql)
# 獲取一條記錄
# fetchall可以獲取所有記錄列表
res = cursor.fetchone()
print(res)
# 關(guān)閉數(shù)據(jù)庫(kù)連接
conn.close()
3、Mysql數(shù)據(jù)庫(kù)
這里使用的是pymysql模塊來(lái)操作Mysql數(shù)據(jù)庫(kù)
#Mysql
importpymysql
conn = pymysql.connect(host='192.168.1.1',port=3308,user='root',
passwd='root',db='testdb',charset='utf8')
# 使用cursor()方法獲取操作游標(biāo)
cursor = conn.cursor()
# SQL 查詢語(yǔ)句
sql ='select*from testtable'
# 執(zhí)行SQL語(yǔ)句
cursor.execute(sql)
# 獲取一條記錄
# fetchall可以獲取所有記錄列表
res = cursor.fetchone()
print(res)
# 關(guān)閉數(shù)據(jù)庫(kù)連接
conn.close()
聯(lián)系客服