Python 入门第一课
本文直接学习python连接数据库基本知识:
- Python环境搭建
- Python连接Mysql数据库
- Python连接oracle数据库
Python环境搭建
Python不做过多的介绍,本文安装的是3.5.0版本,开发工具使用PyCharm,安装步骤请参照。 —— [ python安装步骤 ]
Python连接Mysql数据库
PyCharm导入Python需要的包方法:选中项目->file->project:项目名称->Project Interpreter->点击右上角+号,输入引入的包名PyMySQL 0.9.2 0.9.2,下载即可以使用。
映像地址是192.168.99.100,端口号为容器端口号:53306
import pymysql
# 打开数据库连接
#db = pymysql.connect('192.168.99.100', '****', '****', 'ompbase','53306')
db=pymysql.connect(host='192.168.99.100',port=53306,user='root',passwd='lydia123456',db='ompbase',charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭数据库连接
db.close()
Python连接oracle数据库
PyCharm导入Python需要的包方法:选中项目->file->project:项目名称->Project Interpreter->点击右上角+号,输入引入的包名cx-Oracle 5.3,下载即可以使用。
映像地址是192.168.99.100,端口号为容器端口号:1521
import cx_Oracle
username="system"
userpwd="oracle"
host="192.168.99.100"
port=1521
dbname="xe"
dsn=cx_Oracle.makedsn(host, port, dbname)
connection=cx_Oracle.connect(username, userpwd, dsn)
cursor = connection.cursor()
sql = "select * from myuser"
cursor.execute(sql)
result = cursor.fetchall()
count = cursor.rowcount
print ("=====================" )
print ("Total:", count)
print ("=====================")
for row in result:
print (row)
cursor.close()
connection.close()