Python连接数据主要用SQLAlchemy。
SQLAlchemy是最有名的ORM框架。
首先通过pip或easy_install 安装 SQLAlchemy
pip install sqlalchemy
from sqlalchemy import create_engine
# 连接 sqlite内存数据库
engine = create_engine('sqlite:///:memory:')
# 连接 sqlite文件数据库
# where is relative:
engine = create_engine('sqlite:///foo.db')
# or absolute, starting with a slash:
engine = create_engine('sqlite:absolute/path/to/foo.db')
# 连接 mysql
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')
#连接 oracle
engine = create_engine('oracle://scott:[email protected]:1521/sidname')
#连接SQL Server
engine = create_engine('mssql+pyodbc://mydsn')
#or
engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')
#连接postgresql
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
create_engine()用来初始化数据库连接。SQLAlchemy用一个字符串表示连接信息:
'数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'
参考:[廖雪峰Python教程]
折腾了一天,在mac上安装好了cx_Oracle库。具体步骤如下:
Installation
1. Download the desired Instant Client ZIP files. All installations require the Basic or Basic Lite package.
2. Unzip the packages into a single directory such as "/opt/oracle/instantclient_11_2" that is accessible to your application.
3. Create the appropriate libclntsh.dylib and libocci.dylib links for the version of Instant Client. For example:
cd /opt/oracle/instantclient_11_2
ln -s libclntsh.dylib.11.1 libclntsh.dylib
ln -s libocci.dylib.11.1 libocci.dylib
4. Set the environment variable DYLD_LIBRARY_PATH to the directory created in Step 2, for example:
export DYLD_LIBRARY_PATH=/opt/oracle/instantclient_11_2:$DYLD_LIBRARY_PATH
5. To use supplied binaries such as SQL*Plus, update your PATH environment variable, for example:
export PATH=/opt/oracle/instantclient_11_2:$PATH
6. Start your application.
# tnsnames.ora Network Configuration File: D:\oracle\product\10.2.0\client_1\network\admin\tnsnames.ora
# Generated by Oracle configuration tools.
ORCL =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = orcl)
$ sudo easy_install cx_Oracle
$ brew install freetds
去官网下载mysql,我选的社区版。
win7 64位,MySQLdb直接用pip install 安装不上,出现这样的错误:
_mysql.c
_mysql.c(42) : fatal error C1083: 无法打开包括文件:“config-win.h”: No such
file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BI
N\\cl.exe' failed with exit status 2
百度搜索解决方案,在csdn下载MySQL-python-1.2.3.win32-py2.7 安装包就可行,http://download.csdn.net/download/five3/4488892。