日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Python訪問數(shù)據(jù)庫

 首家i55ryzehof 2018-11-27

說明:

在實際工作中,我們經(jīng)常要使用Python對數(shù)據(jù)庫進行操作(增刪改查)。不同的數(shù)據(jù)庫我們需要下載不同的使用模塊,例如我們需要訪問Oracle數(shù)據(jù)庫和Mysql數(shù)據(jù),你需要下載Oracle和MySQL數(shù)據(jù)庫模塊。

Python 標準數(shù)據(jù)庫接口為 Python DB-API,Python 數(shù)據(jù)庫接口支持非常多的數(shù)據(jù)庫,你可以選擇適合你項目的數(shù)據(jù)庫。詳細可以訪問官方文檔查看相關(guān)信息。

https://wiki./moin/DatabaseInterfaces

本次介紹主流數(shù)據(jù)庫的連接:Oracle、Sql Server、Mysql

1、Oracle數(shù)據(jù)庫

這里使用的是cx_Oracle模塊來操作Oracle數(shù)據(jù)庫

#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()方法獲取操作游標

cursor = connection.cursor()

# SQL 查詢語句

sql ='select*from testtable'

# 執(zhí)行SQL語句

cursor.execute(sql)

# 獲取一條記錄

# fetchall可以獲取所有記錄列表

res = cursor.fetchone()

print(res)

# 關(guān)閉數(shù)據(jù)庫連接

connection.close()

2、Sql Server數(shù)據(jù)庫

這里使用的是pyodbc模塊來操作Sql Server數(shù)據(jù)庫

#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()方法獲取操作游標

cursor = conn.cursor()

# SQL 查詢語句

sql ='select*from testtable'

# 執(zhí)行SQL語句

cursor.execute(sql)

# 獲取一條記錄

# fetchall可以獲取所有記錄列表

res = cursor.fetchone()

print(res)

# 關(guān)閉數(shù)據(jù)庫連接

conn.close()

3、Mysql數(shù)據(jù)庫

這里使用的是pymysql模塊來操作Mysql數(shù)據(jù)庫

#Mysql

importpymysql

conn = pymysql.connect(host='192.168.1.1',port=3308,user='root',

passwd='root',db='testdb',charset='utf8')

# 使用cursor()方法獲取操作游標

cursor = conn.cursor()

# SQL 查詢語句

sql ='select*from testtable'

# 執(zhí)行SQL語句

cursor.execute(sql)

# 獲取一條記錄

# fetchall可以獲取所有記錄列表

res = cursor.fetchone()

print(res)

# 關(guān)閉數(shù)據(jù)庫連接

conn.close()

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多