[英]How do I insert my Python dictionary into my SQL Server database table?
I have a dictionary with 3 keys which correspond to field names in a SQL Server table. 我有一本具有3个键的字典,这些键对应于SQL Server表中的字段名称。 The values of these keys come from an excel file and I store this dictionary in a dataframe which I now need to insert into a SQL table.
这些键的值来自一个excel文件,我将该字典存储在一个数据帧中,现在我需要将其插入到SQL表中。 This can all be seen in the code below:
所有这些都可以在下面的代码中看到:
import pandas as pd
import pymssql
df=[]
fp = "file path"
data = pd.read_excel(fp,sheetname ="CRM View" )
row_date = data.loc[3, ]
row_sita = "ABZPD"
row_event = data.iloc[12, :]
df = pd.DataFrame({'date': row_date,
'sita': row_sita,
'event': row_event
}, index=None)
df = df[4:]
df = df.fillna("")
print(df)
My question is how do I insert this dictionary into a SQL table now? 我的问题是现在如何将该字典插入SQL表中?
Also, as a side note, this code is part of a loop which needs to go through several excel files one by one, insert the data into dictionary then into SQL then delete the data in the dictionary and start again with the next excel file. 另外,作为旁注,此代码是循环的一部分,该循环需要一个一个地遍历几个excel文件,将数据插入字典中,然后插入SQL中,然后删除字典中的数据,然后从下一个excel文件开始。
You could try something like this: 您可以尝试这样的事情:
import MySQLdb
# connect
conn = MySQLdb.connect("127.0.0.1","username","passwore","table")
x = conn.cursor()
# write
x.execute('INSERT into table (row_date, sita, event) values ("%d", "%d", "%d")' % (row_date, sita, event))
# close
conn.commit()
conn.close()
You might have to change it a little based on your SQL restrictions, but should give you a good start anyway. 您可能必须根据您的SQL限制对其进行一些更改,但是无论如何应该为您提供一个良好的开端。
For the pandas dataframe, you can use the pandas built-in method to_sql to store in db. 对于pandas数据框 ,可以使用pandas内置方法to_sql存储在db中。 Following is the way to use it.
以下是使用它的方法。
import sqlalchemy as sa
params = urllib.quote_plus("DRIVER={};SERVER={};DATABASE={};Trusted_Connection=True;".format("{SQL Server}",
"<db_server_url>",
"<db_name>"))
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = sa.create_engine(conn_str)
df.to_sql(<table_name>, engine,schema=<schema_name>, if_exists="append", index=False)
For this method you you will need to install sqlalchemy
package. 对于此方法,您将需要安装
sqlalchemy
软件包。
pip install sqlalchemy
You will also need to setup the MSSql DSN on the machine. 您还需要在计算机上设置MSSql DSN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.