簡體   English   中英

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

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

到目前為止,我一直在使用SQL API, php文件以及Python中的requests模塊從SQL服務器請求數據。 所以這是我的代碼:

# 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()

現在,我完成工作后,就形成了一個像這樣的數據框:

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

現在使用類似的requests模塊,有一種方法可以編寫如下內容: INSERT INTO table_name...並將數據幀上載到SQL表中。

我無法弄清的主要問題是:

i)如何一次性將dataframe列值上傳到表中?

ii)如果無法通過請求模塊實現,我還有其他方法可以使用Python代碼直接從jupyter-notebook將Pandas數據幀值上傳到SQL-server表嗎?

要將數據幀導入到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