设为首页 加入收藏

TOP

Python Opearte SQLAlchemy Do Something
2017-09-30 16:56:04 】 浏览:3682
Tags:Python Opearte SQLAlchemy Something

近段时间在看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:password@host:port/database 标准连接数据库规范
 
MS-SQL连接案例
Microsoft SQL Server

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

# pyodbc
engine = create_engine('mssql+pyodbc://scott:tiger@mydsn')

# pymssql
engine = create_engine('mssql+pymssql://scott:tiger@hostname: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)

这样可以通过相关表的关联就能查询数据。

有好多东西,再叙。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇CoolPlist 帧动画自动生成工具 下一篇Flask框架学习笔记(API接口管理..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目