[python to MS SQL]:替代dataframe.to_sql,不使用sqlalchemy.create_engine()和使用pypyodbc

发布于 2025-02-06 06:31:37 字数 829 浏览 1 评论 0原文

方案:

1.我正在尝试将数据框架直接插入SQL表中。

engine_azure = sqlalchemy.create_engine(sqlchemy_conn_str,echo=True,fast_executemany = True, poolclass=NullPool)
conn = engine_azure.connect()
df_final_result.to_sql('Employee', engine_azure,schema='dbo', index = False, if_exists = 'replace')

2.因此,使用pypyodbc连接有上述.to_sql的替代方法吗?

3. BELOW代码我们可以使用,但我有90列,因此我想避免使用以下迭代的代码。

import pyodbc
cnxn = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}', server='xyz', database='xyz',               
               trusted_connection='yes'
cursor = cnxn.cursor()
for index, row in df2.iterrows():
     cursor.execute("INSERT INTO Employee(ContactNumber,Name,Salary,Address) values(?,?,?,?,?,?)", row.ContactNumber, row.Name, row.Salary,row['Address'])

cnxn.commit()
cnxn.close()

Scenario:

1.I am trying to insert the dataframe directly into SQL Table.

engine_azure = sqlalchemy.create_engine(sqlchemy_conn_str,echo=True,fast_executemany = True, poolclass=NullPool)
conn = engine_azure.connect()
df_final_result.to_sql('Employee', engine_azure,schema='dbo', index = False, if_exists = 'replace')

2.So is there any alternative to the above .to_sql using pypyodbc connection?

3.Below code we can use but i have 90 columns, so i want to avoid code with below iteration.

import pyodbc
cnxn = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}', server='xyz', database='xyz',               
               trusted_connection='yes'
cursor = cnxn.cursor()
for index, row in df2.iterrows():
     cursor.execute("INSERT INTO Employee(ContactNumber,Name,Salary,Address) values(?,?,?,?,?,?)", row.ContactNumber, row.Name, row.Salary,row['Address'])

cnxn.commit()
cnxn.close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文