简体   繁体   English

使用Python将Pandas Dataframe插入SQL Server-Jupyter Notebook

[英]INSERT Pandas Dataframe to SQL-Server using Python - Jupyter Notebook

Till now, I've been requesting data from my SQL-server, using an API, php file basically and using the requests module in Python. 到目前为止,我一直在使用SQL API, php文件以及Python中的requests模块从SQL服务器请求数据。 So here's my code for that: 所以这是我的代码:

# importing the requests library
import requests

# api-endpoint
URL = "https://******.co.in/******/queryRandom.php"

# location given here
token= '***************'

query= 'SELECT userId,createdAt,.... FROM xyz WHERE date >= CURDATE() - INTERVAL 60 DAY'

# defining a params dict for the parameters to be sent to the API
PARAMS = {'token':token, 'query':query}

# sending get request and saving the response as response object
r = requests.post(url = URL, data = PARAMS)
df=pd.DataFrame(r.json())
df.head()

Now after I'm done with my work, I formed a dataframe like this: 现在,我完成工作后,就形成了一个像这样的数据框:

Sl.No.  date    nameofthepic    
1   26-08-2018  10-must-see-waterfalls-in-karnataka-8081714182d8    
2   26-08-2018  a-month-in-backpack-one-girl-one-goal-to-explore-the-himalayas-22813ee67e15 
3   26-08-2018  a-month-in-backpack-one-girl-one-goal-to-explore-the-himalayas-week-1-8d113ee673db  
4   26-08-2018  a-month-in-backpack-one-girl-one-goal-to-explore-the-himalayas-week-1-22b13ee67b87  
5   26-08-2018  backpacking-for-a-month-in-the-himalayas-week-1-30813ee674a6

Now using the similar requests module, is there a way I can write something like this: INSERT INTO table_name... and upload the dataframe into the SQL table. 现在使用类似的requests模块,有一种方法可以编写如下内容: INSERT INTO table_name...并将数据帧上载到SQL表中。

The main problem I'm not able to figure out is: 我无法弄清的主要问题是:

i) How do I upload the dataframe column values into the table in one go? i)如何一次性将dataframe列值上传到表中?

ii) If its not possible through requests module, is there any other way I can upload the Pandas dataframe values into SQL-server table directly from jupyter-notebook using Python code? ii)如果无法通过请求模块实现,我还有其他方法可以使用Python代码直接从jupyter-notebook将Pandas数据帧值上传到SQL-server表吗?

To import this dataframe into a MySQL table: 要将数据帧导入到MySQL表中:

# Import dataframe into MySQL
import sqlalchemy
database_username = 'ENTER USERNAME'
database_password = 'ENTER USERNAME PASSWORD'
database_ip       = 'ENTER DATABASE IP'
database_name     = 'ENTER DATABASE NAME'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.format(database_username, database_password, database_ip, database_name))
frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='append')

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

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