Python Opearte SQLAlchemy Do Something

來源:互聯網
上載者:User

標籤:

近段時間在看SQLAlchemy,總之萬事開頭難,但是麼辦法。

Database Urls

The create_engine() function produces an Engine object based on a URL. These URLs follow RFC-1738, and usually can include username, password, hostname, database name as well as optional keyword arguments for additional configuration. In some cases a file path is accepted, and in others a “data source name” replaces the “host” and “database” portions. The typical form of a database URL is:

dialect+driver://username:[email protected]:port/database 標準串連資料庫規範
 
MS-SQL串連案例
Microsoft SQL Server

The SQL Server dialect uses pyodbc as the default DBAPI. pymssql is also available:

# pyodbcengine = create_engine(‘mssql+pyodbc://scott:[email protected]‘)# pymssqlengine = create_engine(‘mssql+pymssql://scott:[email protected]:port/dbname‘)

More notes on connecting to SQL Server at Microsoft SQL Server.

這裡面測試用的是pyodbc進行串連的,分兩種

engine=create_engine("mssql+pyodbc://sa:@192.168.6.112:1433/FactoryHome?driver=SQL+Server+Native+Client+10.0")

還有一種就是通過微軟的dsn進行串連,如不知道dsn串連,可以百度一下看看是什麼意思

對資料的插入

from sqlalchemy import *engine=create_engine("mssql+pyodbc://sa:@192.168.6.112:1433/FactoryHome?driver=SQL+Server+Native+Client+10.0")metadata=MetaData()Table_1=Table("Table_1",metadata,Column("Code",String(10)),Column("Name",String(10)))ins=Table_1.insert().values(Code=‘cccccc‘,Name=‘王二‘)conn=engine.connect()result=conn.execute(ins)

參數化的形式,感覺有點感覺比拼接SQL來的快。

result=conn.execute(Table_1.insert(),Code=‘kkkkk‘,Name=‘網易‘)

對於給定的參數也可以這樣傳值。

對於資料的查詢,也必須的先構造一個TABLE,然後對應的欄位進行查詢

from sqlalchemy import *engine=create_engine("mssql+pyodbc://sa:@192.168.6.112:1433/FactoryHome?driver=SQL+Server+Native+Client+10.0")metadata=MetaData()Table_1=Table("Table_1",metadata,Column("Code",String(10)),Column("Name",String(10)))conn=engine.connect()result=conn.execute(select([Table_1]))for row in result:    print(row)

SQLAlchemy最好的方式就是能像SQL語句一樣能實現join串連查詢

>>> s = select([users, addresses]).where(users.c.id == addresses.c.user_id)SQL>>> for row in conn.execute(s):...     print(row)

這樣可以通過相關表的關聯就能查詢資料。

有好多東西,再敘。

Python Opearte SQLAlchemy Do Something

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.