首页 > 解决方案 > python - 到 SQL Server 的数据框

问题描述

请不要使用 sqlalchemy,因为我没有端口信息 - 我只有服务器名称、数据库以及用户名和密码。

import numpy as np
import pandas as pd

df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
               'num_wings': [2, 0, 0, 0],
               'num_specimen_seen': [8, 2, 5, 6]},
             )
print(df)

我在 SQL Server 中有一个表,Animal名为Legs, wings, SpecSeen;

CREATE TABLE Habitat 
(
     Legs int,
     wings int, 
     SpecSeen nvarchar(50)
)

ServerName: SQL15A
Database: Habitat
SQL username: QATuser
Password: ****

我需要将此 DataFrame 插入到 SQL Server 表中,也不需要将 DataFrame 索引列插入到数据库表中。

标签: pythonsql-serverdataframe

解决方案


这里寻求帮助

import sqlalchemy
import pyodbc
engine = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@<dsnname>")

# write the DataFrame to a table in the sql database
df.to_sql("table_name", engine)

推荐阅读