Windows下python连接MySQL和Oracle数据库

MySQL

(1)如果Python的版本是2.x的话,需要MySQLdb模块

根据Python多少位下载对应版本:

32位:https://pypi.python.org/pypi/MySQL-python/1.2.5
64位:http://arquivos.victorjabur.com/python/modules/MySQL-python-1.2.3.win-amd64-py2.7.exe

下载对应版本,直接安装

保持电脑联网,并且将python的安装路径添加到环境变量,那么在DOS窗口下输入下面一句命令即可自动下载安装:

pip install MySQL-python==1.2.5

在python程序的头部加上

import MySQLdb

(2)如果是3.x 版本的话,则需要pymysql模块

同理,电脑联网下在DOS窗口下输入:

pip install pymysql
在python程序的头部加上
import pymysql

我的是python3.6,下面是测试连接MySQL的代码:

# -*- coding: UTF-8 -*-

import pymysql
import pymysql.cursors

connection = pymysql.connect(host='localhost', #MySQL数据库的IP地址
                             user='用户名',  
                             password='连接数据库的密码',
                             db='数据库的名称',
                             port=3306,
                             charset='utf8') #注意是utf8而不是utf-8
try:
    with connection.cursor() as cursor:
        sql_1 = 'select * from people'
        cout_1 = cursor.execute(sql_1)
        print("数量:"+str(cout_1))
        for row in cursor.fetchall():
            print("num:",str(row[0]),'name',str(row[1]),'gender',str(row[2]))

        sql_2 = 'insert into people(num,name,gender) values("44563","John",1)'
        cout_2 = cursor.execute(sql_2)
        print("数量:"+str(cout_2))
        connection.commit()
finally:
    connection.close()

Oracle

需要cx_Oracle包的支持

电脑联网下在DOS窗口下输入:

python -m pip install cx_Oracle --upgrade

详见官网http://cx-oracle.readthedocs.io/en/latest/installation.html

# -*- coding: UTF-8 -*-

import cx_Oracle  #导入连接Oracle数据库需要的包

#方法一:用户名、密码和监听分开写
db = cx_Oracle.connect('username/password@orcl')
db.close()
 
#方法二:用户名、密码和监听写在一起
db = cx_Oracle.connect('username','password','orcl')
db.close()
 
#方法三:配置监听并连接
tns = cx_Oracle.makedsn('host',1521,'orcl')
db = cx_Oracle.connect('username','password',tns)
db.close()

猜你喜欢

转载自blog.csdn.net/li_wei_quan/article/details/79974999