【问题标题】:Python: Post json to MySql DatabasePython:将 json 发布到 MySql 数据库
【发布时间】:2021-10-03 00:07:22
【问题描述】:

我对如何将我的 json 数据推送到 MySql 有点不知所措。我有光标。我需要先创建一个表吗?有没有一种方法可以简单地将我的 json 数据直接推入?

with open("trades.json") as f:
    trades_data = json.load(f)

trades_data = reconfigure_data(trades_data)

db = mysql.connector.connect(
    host="localhost",
    user=os.environ.get('MYSQL_DB_USER'),
    password=os.environ.get('MYSQL_DB_USER_PASS',
    database='trades')
)

cursor = db.cursor()

【问题讨论】:

    标签: python mysql json


    【解决方案1】:

    我找到了有效的语法:

    cursor = db.cursor()
    # create table on database
    sql = "CREATE TABLE IF NOT EXISTS `test` (`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `objectid` VARCHAR(100), `type` VARCHAR(5), `ownerid` VARCHAR(100), `color` VARCHAR(15), `shape` VARCHAR(15), `size` VARCHAR(15), PRIMARY KEY (`id`) );"
    print(sql)
    cursor.execute(sql)
    
    with open("trades.json") as f:
        trades_data = json.load(f)
    
        for trade in trades_data:
            for right in trade['rights']:
                sql = f"INSERT INTO test (objectid, type, ownerid, color, shape, size)     VALUES ('{trade['objectid']}', '{trade['type']}', '{trade['ownerid']}', '{right['color']}', '{right['shape']}', '{right['size']}' )"
               
                cursor.execute(sql)
                db.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多