简体   繁体   English

将数据框作为新表导出到MSSQL Server中

[英]Export a Dataframe into MSSQL Server as a new Table

I have written a Code to connect to a SQL Server with Python and save a Table from a database in a df. 我已经编写了一个代码,以使用Python连接到SQL Server并在df中从数据库保存表。

from pptx import Presentation
import pyodbc
import pandas as pd
cnxn = pyodbc.connect("Driver={ODBC Driver 11 for SQL Server};"
                      "Server=Servername;"
                      "Database=Test_Database;"
                      "Trusted_Connection=yes;")
df = pd.read_sql_query('select * from Table1', cnxn)

Now I would like to modify df in Python and save it as df2. 现在,我想在Python中修改df并将其另存为df2。 After that I would like to export df2 as a new Table (Table2) into the Database. 之后,我想将df2作为新表(Table2)导出到数据库中。

I cant find anything about exporting a dataframe to a SQL Server. 我找不到有关将数据框导出到SQL Server的任何信息。 you guys know how to do it? 你们知道怎么做吗?

You can use df.to_sql() for that. 您可以为此使用df.to_sql() First create the SQLAlchemy connection, eg 首先创建SQLAlchemy连接,例如

from sqlalchemy import create_engine
engine = create_engine("mssql+pyodbc://scott:tiger@myhost:port/databasename?driver=SQL+Server+Native+Client+10.0")

See this answer for more details the connection string for MSSQL. 有关更多详细信息,请参见此答案 ,以了解MSSQL的连接字符串。

Then do: 然后做:

df.to_sql('table_name', con=engine)

This defaults to raising an exception if the table already exists, adjust the if_exists parameter as necessary. 如果表已经存在,则默认情况下会引发异常,请根据需要调整if_exists参数。

This is how I do it. 这就是我的方法。

# Insert from dataframe to table in SQL Server
import time
import pandas as pd
import pyodbc

# create timer
start_time = time.time()
from sqlalchemy import create_engine


df = pd.read_csv("C:\\your_path\\CSV1.csv")

conn_str = (
    r'DRIVER={SQL Server Native Client 11.0};'
    r'SERVER=ServerName;'
    r'DATABASE=DatabaseName;'
    r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)

cursor = cnxn.cursor()

for index,row in df.iterrows():
    cursor.execute('INSERT INTO dbo.Table_1([Name],[Address],[Age],[Work]) values (?,?,?,?)', 
                    row['Name'], 
                    row['Address'], 
                    row['Age'],
                    row['Work'])
    cnxn.commit()
cursor.close()
cnxn.close()

# see total time to do insert
print("%s seconds ---" % (time.time() - start_time))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM