我正在尝试使用 sqlalchemy 从 ubuntu 远程连接 Windows 中的 MSSQL。我创建了如下所示的 DSN
数据库信息.py:
username = 'XXX'
pw = 'XXX'
host = '190.122.12.214'
drivername = 'SQL Server'
database = 'XXX'
extra_param=''
我将 dbinfo.py 文件导入 db_handler.py :
import transaction
from z3c.saconfig import Session as SASession
from z3c.saconfig import EngineFactory
from zope import component
from zope.sqlalchemy import mark_changed
# sqlalchemy
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from redindia.loginpage import dbinfo
info = {
'username' : dbinfo.username,
'pw' : dbinfo.pw,
'host' : dbinfo.host,
'drivername' : dbinfo.drivername,
'database' : dbinfo.database,
'extra_param' : ''
}
drivername = str(info['drivername'])
username = str(info['username'])
host = str(info['host'])
database = str(info['database'])
extra_param = str(info['extra_param'])
def getDb():
pass
def getSession(testing=False):
try:
return SASession()
except component.ComponentLookupError:
pass
# construct url to open database
_testing_ = ''
if testing:
_testing_ = '_testing'
if info['pw'] != '':
DSN = drivername+'://'+username+':' + info['pw'] +'@'+host+'/'+database+_testing_+'?charset=utf8'+extra_param
else:
DSN = drivername+'://'+username+'@'+host+'/'+database+_testing_+'?charset=utf8'+extra_param
engine_factory = EngineFactory(DSN, pool_recycle=7200)
engine = engine_factory()
## create a global session
from z3c.saconfig import GloballyScopedSession
utility = GloballyScopedSession(bind=engine) # i think, without engine, it will find above provided one...
from z3c.saconfig.interfaces import IScopedSession
component.provideUtility(utility, provides=IScopedSession)
return SASession()
session = getSession()
engine = session.get_bind()
Base = declarative_base(engine)
Base.metadata.reflect()
tables = Base.metadata.tables
然后连接下面提到的细节
def callStoreProcedure(self):
form = self.request.form
area = form.get('Area')
session = getSession()
result = session.execute("select * from BBBB")
result_set = result.fetchall()
return result_set
我配置 ODBC 连接设置
等/odbc.ini:
[SQL Server]
Description=my dsn
Driver=SQL Server
Database=XXX
Servername=190.122.12.214
UID=XXX
PWD=XXX
等/odbcinst.ini:
[SQL Server]
Description = sql Driver
Driver = /usr/local/lib/libtdsodbc.so
Setup=/usr/local/lib/libtdsS.so
UsageCount = 1
我配置了上面的设置。但我无法连接 MSSQL。我收到如下错误
"ArgumentError: Could not parse rfc1738 URL from string 'SQL Server://XXX:XXX@190.122.12.214/XXX?charset=utf8'"
请任何人都可以帮我解决这个问题。在此先感谢。
最佳答案
SQLAlchemy 引擎 URL 应该以 mssql
开头。或 mssql+pyodbc
.见Engine Configuration documentation .
关于python - 如何使用 sqlalchemy 从 ubuntu 连接远程 Windows MSSQL 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20654475/