从数据库里python获取数据存到本地数据库

从数据库里python获取数据存到本地数据库,第1张

python项目中从接口获取数据并存入本地数据库

首先用postman测试接口

根据请求方式将数据存入数据库中

首先用postman测试接口

通过url,选择相应的请求方式,头部,数据格式,点击send看能否获取数据

根据请求方式将数据存入数据库中

下面是post请求方式def get() URL = '' HEADERS = {'Content-Type': 'application/json'} JSON = {} response = request.post(URL,headers=HEADERS,json=JSON) #json.loads()用于将str类型的数据转成dict jsondata = json.load(response.txt) for i in jsondata: date1 = i[data] type1 = i[type] ... #拼接sql语句 sql="" conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable")  cursor=conn.cursor()  ursor.execute(sql)

利用mysql插件 pymysql;写insert语句直接插入到数据库

安装:pip install pymysql。

代码:excute_sql方法是执行更新,插入 *** 作。get_datasset方法是查询。

# coding: utf-8

import pymysql.cursors

def execute_sql(sql):

    conn = pymysql.connect(host='127.0.0.1',port = 3306,user='root',passwd='123456',db ='db',charset="utf8")

    try:

        with conn.cursor() as cursor:

            cursor.execute(sql)

            conn.commit()

    finally:

        conn.close()

def get_dataset(sql):

    conn = pymysql.connect(host='127.0.0.1',port = 3306,user='root',passwd='123456',db ='db',charset="utf8")

    try:

        with conn.cursor() as cursor:

            cursor.execute(sql)

            return cursor.fetchall()

    finally:

        conn.close()


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9997784.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-04
下一篇2023-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存