简体   繁体   English

如何将Python字典插入SQL Server数据库表中?

[英]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.

相关问题 Python-SQL:如何将这些变量插入数据库的表中? - Python - SQL: How do I insert these variables into a table in a database? 如何使用 Python 3.7 修复我的代码以插入 SQL 服务器 - How do I fix my code for insert into SQL Server with Python 3.7 如何在通过变量搜索时从一个表中 Select user_ID 并插入到另一个表中? Python 我的 SQL - How do I Select user_ID from one table and insert into another while searching by a variable? Python my SQL 如何将变量的值插入 MySQL 数据库? - How do I insert the value of my variable into my MySQL database? 如何将我的数据库插入我的QTableWidget表? - How to insert my database into my QTableWidget table? 如何在GUI中以python表格格式显示SQL数据库? - How can I display my SQL database within a table format in python within my GUI? 如何从CSV文件获取值以使用python加载到SQL数据库中? - How do I get to my values from a CSV file to load into my SQL database with python? 如何在列名是变量的SQL表中插入列? - How do I insert columns in my SQL table, where column name is a variable? 如何防止我的 Python 程序在我的 SQL 服务器上使用过多的 memory? - How do I keep my Python program from using too much memory on my SQL Server? 使用 python 我正在尝试将 ADMIN_ID 作为 None 插入到 SQL 中的数据库中,并将我的 date_time 转换为合适的格式插入表中 - using python I'm trying to insert ADMIN_ID as None in to a database in SQL and my date_time that converted into a suitable format into a table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM