【问题标题】:sqlalchemy MSSQL+pyodbc schema nonesqlalchemy MSSQL+pyodbc 模式 无
【发布时间】:2020-10-08 15:21:12
【问题描述】:

我正在尝试通过 sqlalchemy 连接到 SQL Server 2019。我同时使用 mssql+pyodbc 和 msql+pyodbc_mssql,但在这两种情况下它都无法连接,总是返回未定义的 default_schema_name。 已检查数据库、定义的用户架构和所有内容。

例子:

from sqlalchemy import create_engine
import urllib 
from sqlalchemy import create_engine
server = 'server' 
database = 'db' 
username = 'user' 
password = 'pass' 
#cnxn = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';Trusted_Connection=yes'
cnxn = 'DSN=SQL Server;SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';Trusted_Connection=yes'
params = urllib.parse.quote_plus(cnxn)

engine = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
cnxn = engine.connect()

返回无,方言.default_schema_name
AttributeError: 'MSDialect_pyodbc' 对象没有属性 'default_schema_name'

TIA.....

【问题讨论】:

  • 你解决了这个问题吗?
  • 不。显然 SQL 服务器的方言不正确,它不起作用。
  • 我确实最终得到了这个设置,想要我发布答案吗?
  • 愿意。我尝试了很多方法,sqlalchemy 似乎永远无法与 SQL server 2019 正确对话。
  • Righto,下面发布的示例。取自工作脚本。最好的提示是确保您安装了适用于 SQL 服务器的 Microsoft ODBC 驱动程序,而不仅仅是 pyodbc。第 17 版对我有用。

标签: python sql-server sqlalchemy sql-server-2019


【解决方案1】:

希望以下内容为最小可行样本提供了足够的信息。我在一个更大的脚本中使用它每天 3 次移动 1200 万行,因此我包含了一个我从其他地方捏造的分块示例。

#Set up enterprise DB connection
# Enterprise DB to be used
DRIVER = "ODBC Driver 17 for SQL Server"
USERNAME = "SQLUsername"
PSSWD = "SQLPassword"
SERVERNAME = "SERVERNAME01"
INSTANCENAME = "\SQL_01"
DB = "DATABASE_Name"
TABLE = "Table_Name"

#Set up SQL database connection variable / path
#I have included this as an example that can be used to chunk data up
conn_executemany = sql.create_engine(
    f"mssql+pyodbc://{USERNAME}:{PSSWD}@{SERVERNAME}{INSTANCENAME}/{DB}?driver={DRIVER}", fast_executemany=True
)




#Used for SQL Loading from Pandas DF
def chunker(seq, size):
    return (seq[pos : pos + size] for pos in range(0, len(seq), size))

#Used for SQL Loading from Pandas DF
def insert_with_progress(df, engine, table="", schema="dbo"):
    con = engine.connect()

    # Replace table
    #engine.execute(f"DROP TABLE IF EXISTS {schema}.{table};") #This only works for SQL Server 2016 or greater
    try:
      engine.execute(f"DROP TABLE Temp_WeatherGrids;")
    except:
      print("Unable to drop temp table")
    
    try:
      engine.execute(f"CREATE TABLE [dbo].[Temp_WeatherGrids]([col_01] [int] NULL,[Location] [int] NULL,[DateTime] [datetime] NULL,[Counts] [real] NULL) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];")
    except:
      print("Unable to create temp table")
    

    # Insert with progress
    SQL_SERVER_CHUNK_LIMIT = 250000
    chunksize = math.floor(SQL_SERVER_CHUNK_LIMIT / len(df.columns))

    for chunk in chunker(df, chunksize):
        chunk.to_sql(
            name=table,
            con=con,
            if_exists="append",
            index=False
        )


if __name__ == '__main__':

    # intialise data. Example -  make your own dataframe. DateTime should be pandas datetime objects. 
    data = {'Col_01':[0, 1, 2, 3], 
            'Location':['Bar', 'Pub', 'Brewery', 'Bottleshop'],
            'DateTime':["1/1/2018", "1/1/2019", "1/1/2020", "1/1/2021"],
            'Counts':[1, 2, 3, 4} 
  
    # Create DataFrame 
    df = pd.DataFrame(data) 

    insert_with_progress(df, conn_executemany, table=TABLE)
    del [df]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-07
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2018-04-15
    • 2011-07-14
    相关资源
    最近更新 更多