SQLAlchemy連接數據庫


 

 

簡介:

本文默認你已經有了一定的數據庫基礎。
我們不喜歡寫原生SQL語句,那個寫着費勁,日常開發時候,我們怎么CRUD數據庫呢?一般使用ORM,對象關系映射(英語:Object Relational Mapping,簡稱ORM)。
主力使用的是python語言,那么python中最好用的ORM就是sqlalchemy。

一:連接參數

sqlalchemy使用 create_engine() 函數從URL生成一個數據庫鏈接對象,URL遵循 RFC-1738標准。我也不懂。大概就是要有用戶名,密碼,地址,端口,數據庫名,還有一些可選參數。一個標准的鏈接URL是這樣的:
dialect+driver://username:password@host:port/database
dialect,是數據庫類型,大概包括:sqlite, mysql, postgresql, oracle, or mssql.
driver,是使用的數據庫API,驅動,連接包,隨便叫什么吧。
username,用戶名
password,密碼
host,網絡地址,可以用ip,域名,計算機名,當然是你能訪問到的。
port,數據庫端口。
databas,數據庫名。
其實這些也就dialect和dirver需要解釋。

二:連接sqlite3

1,驅動
sqlite3是個文件數據庫,不需要什么驅動,或者說python內置了驅動。
2,標准連接參數
# sqlite://<nohostname>/<path>
沒有hostname
3,各種鏈接參數
# 相對路徑,就是這個python文件同目錄下foo.db
engine = create_engine('sqlite:///foo.db')
#絕對路徑
#Unix/Mac下用四條////表示
engine = create_engine('sqlite:////absolute/path/to/foo.db')
#Windows下用三條///加盤符路徑用兩條\\
engine = create_engine('sqlite:///C:\\path\\to\\foo.db')
#Windows 也可以這么用三條///加盤符路徑用一條\
engine = create_engine(r'sqlite:///C:\path\to\foo.db')
#數據庫建在內存里。URI保持為空即可
engine = create_engine('sqlite://')

三:連接mysql(mariadb)

sqlalchemy默認使用mysql-python作為鏈接驅動,既default模式
選哪種驅動,就裝哪個包。
1,default默認鏈接方式
engine = create_engine('mysql://scott:tiger@localhost/foo')
2,# mysql-python,聲明使用mysql-python驅動
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')
3,MySQL-connector-python 聲明使用MySQL-connector-python驅動(推薦使用)
engine = create_engine('mysql+mysqlconnector://scott:tiger@localhost/foo')
4,OurSQL 聲明使用OurSQL驅動
engine = create_engine('mysql+oursql://scott:tiger@localhost/foo')

四:連接Microsoft SQL Server

sqlalchemy默認使用 pyodbc作為鏈接驅動。
1,pyodbc
engine = create_engine('mssql+pyodbc://scott:tiger@mydsn')
2,pymssql
engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')

 

五:連接PostgreSQL

PostgreSQL默認使用 psycopg2作為鏈接驅動,既default模式
1, default
engine = create_engine('postgresql://scott:tiger@localhost/mydatabase')
2,psycopg2
engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')
3, pg8000
engine = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase')

 六:連接Oracle

Oracle可能只有 cx_oracle一個驅動包,既default模式和聲明模式一樣。
1,default
engine = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
2,cx_oracle
engine = create_engine('oracle+cx_oracle://scott:tiger@tnsname')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM