說明: 在實際工作中,我們經(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() |
|
來自: 首家i55ryzehof > 《電腦知識》