python requests 鐖彇骞跺啓鍏ysql
鍙互浣跨敤Python鐨剅equests搴撴潵鍙戦丠TTP璇锋眰鑾峰彇鏁版嵁锛岀劧鍚庡皢鏁版嵁瀛樺偍鍒癕ySQL涓
棣栧厛闇瑕佸畨瑁卹equests搴撳拰pymysql搴擄紙鐢ㄤ簬杩炴帴MySQL锛夈傚彲浠ラ氳繃浠ヤ笅鍛戒护杩涜瀹夎锛
pip install requests pymysql
鐒跺悗缂栧啓濡備笅浠g爜绀轰緥锛
import requests
import pymysql.cursors
# 瀹氫箟鐩爣URL
url = "http://odweb.cn"
# 鍙戣捣GET璇锋眰
response = requests.get(url)
data = response.json() # 鍋囪杩斿洖鐨勬槸JSON鏍煎紡鐨勬暟鎹
# 寤虹珛涓嶮ySQL鐨勮繛鎺
connection = pymysql.connect(host='localhost', user='root', password='password', db='database_name')
cursor = connection.cursor()
try:
# 閬嶅巻鏁版嵁骞舵彃鍏ュ埌MySQL琛ㄤ腑
for item in data['items']:
sql = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
values = [item['value1'], item['value2']]
cursor.execute(sql, values)
# 鎻愪氦浜嬪姟
connection.commit()
except Exception as e:
print("Error occurred while inserting into MySQL:", str(e))
finally:
# 鍏抽棴杩炴帴
cursor.close()
connection.close()
涓婅堪浠g爜浼氫粠鎸囧畾鐨刄RL鑾峰彇鏁版嵁锛屽苟灏嗗叾鎻掑叆鍒板悕涓簍able_name鐨凪ySQL琛ㄤ腑銆傚湪杩欎箣鍓嶏紝纭繚宸茬粡鍒涘缓浜嗙浉搴旂殑琛ㄧ粨鏋勩
鏉ユ簮锛歄D浜
浠ヤ笂灏辨槸python requests 鐖彇缃戦〉骞跺啓鍏ysql鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒