簡體   English   中英

如何使用變量將python中的數據插入到mysql數據庫中?

[英]How to use variables to insert data in python to a mysql database?

將數據插入查詢時,如何直接使用變量代替字符串?

import pymysql
import json

# Connect to the database
conn = pymysql.connect(host='localhost',
                       user='test',
                       password='br',
                       db='testing')
cur = conn.cursor()

json_data = json.loads(open("res.json").read())

# currently this is the query I want to execute
query = """INSERT INTO RF.candidate (
    first_name, last_name, phone, email, 
    social, website
) VALUES (
    'David', 'N', '["+1 917 547 7813", "+1 917 547 7823"]', 
    '["testing@gmail.com"]', '["fb.com/rtr"]', '["google.com", "sris.com"]', 
    '{"Degree": {"MBA": {"Majors": [""]}}}',
);"""

cur.execute(query)

# datatypes:
# first_name : varchar
# last_name : varchar
# phone : json
# email : json
# social : json
# website: json
# education: json

電子郵件地址數據在json_data變量中,

print(json_data['email'])
# returns
["testing@gmail.com"]

email_array = json.dumps(json_data['email'])

現在我想在 sql 查詢email列中傳遞變量email_array而不是像上面那樣手動在查詢變量中寫入 json 列表?

我怎樣才能在python中做到這一點?

query = """INSERT INTO RF.candidate (
    first_name, last_name, phone, email, 
    social, website
) VALUES (
    'David', 'N', '["+1 917 547 7813", "+1 917 547 7823"]', 
    '[{}]', '["fb.com/rtr"]', '["google.com", "sris.com"]'
);""".format(EMAIL_VARIABLE)

如果 email 變量是一個數組,則使用{}否則[{}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM