说明:
在实际工作中,我们经常要使用Python对数据库进行操作(增删改查)。不同的数据库我们需要下载不同的使用模块,例如我们需要访问Oracle数据库和Mysql数据,你需要下载Oracle和MySQL数据库模块。
Python 标准数据库接口为 Python DB-API,Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库。详细可以访问官方文档查看相关信息。
https://wiki.python.org/moin/DatabaseInterfaces
本次介绍主流数据库的连接:Oracle、Sql Server、Mysql
1、Oracle数据库
这里使用的是cx_Oracle模块来操作Oracle数据库
#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'
# 执行SQL语句
cursor.execute(sql)
# 获取一条记录
# fetchall可以获取所有记录列表
res = cursor.fetchone()
print(res)
# 关闭数据库连接
connection.close()
2、Sql Server数据库
这里使用的是pyodbc模块来操作Sql Server数据库
#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'
# 执行SQL语句
cursor.execute(sql)
# 获取一条记录
# fetchall可以获取所有记录列表
res = cursor.fetchone()
print(res)
# 关闭数据库连接
conn.close()
3、Mysql数据库
这里使用的是pymysql模块来操作Mysql数据库
#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'
# 执行SQL语句
cursor.execute(sql)
# 获取一条记录
# fetchall可以获取所有记录列表
res = cursor.fetchone()
print(res)
# 关闭数据库连接
conn.close()
联系客服