首先安装pyodbc
可能需要安装unixodbc
sudo apt-get install unixodbc-dev
pip install pyodbc
成功
engine=create_engine("mssql+pyodbc://username:password@DSN/SUSDB")
如果连接已经建立成功:
engine是一个数据库连接的仓库用于处理SQL语句,如果要建立一个连接:
conn = engine.connect()
select:
>>> from sqlalchemy.sql import select
>>> s = select([users])
>>> result = conn.execute(s)
>>> for row in result:
... print(row)
连接mssql出现的各种问题:
error: 首先是连接不上,driver出错:(此时没有用dsn):
https://github.com/ContinuumIO/anaconda-issues/issues/1639
sudo vi /etc/hosts
host test70
sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
sudo vi /etc/apt/sources.list.d/mssql-release.list
deb [arch=amd64] https://packages.microsoft.com/ubuntu/16.04/prod xenial
main
error: driver not specified
解决办法:加上?driver=ODBC+Driver+13+for+SQL+Server
error: 还是报timeout或者driver找不到之类的错误:
解决办法:
- 设置sql server允许远程连接: https://imron.com/support/knowledgebase/configuring-a-sql-server-for-remote-connections/
- 配置dsn: https://support.microsoft.com/en-us/help/965049/how-to-set-up-a-microsoft-sql-server-odbc-data-source
error: login failed for (username)
解决办法:在sql server中新建一个server authentication 的账户,并且要改登录模式,默认的登录模式是Windows authentication
新建了: sqlalchemy:qaz1234!
error: [SQL Server]Cannot open database “SUSDB” requested by the login. The login failed. (4060)
解决办法:https://www.supremainc.com/en/node/618
依照里面的内容进行修改配置sql server authentication login配置
成功!!!!!!!!!!!!!!!!!!!!
测试:
result = engine.execute('select * from dbo.tbRevision')
for row in result:
print row
直接使用engine.execute()来执行sql语句