简体   繁体   中英

create sql file by reading data from yaml file using python

I am new to python. I have yaml file (config.yaml) which contains data like below.

Config:
    - name: identity
      value: 101
    - name: size
      value: 201
    - name: logloc
      value: /tmp/log
    - name: host
      value: xyz.dev.cloud

I am looking for python script to read the above yaml file and create sql file with update statements for each name and value as below .

UPDATE SAMPLE SET PVALUE=<value> WHERE PNAME=<name>

Thanks in advance.

This will, I believe, do what you want:

import yaml

with open('/tmp/config.yaml') as f:
    data = yaml.load(f, Loader=yaml.SafeLoader)

template = "UPDATE SAMPLE SET PVALUE={} WHERE PNAME={}"
statements = [template.format(nv['value'], nv['name']) for nv in data['Config']]

with open("/tmp/update_samples.sql", 'w') as f:
    for statement in statements:
        f.write(statement + '\n')

Contents of /tmp/update_samples.sql :

UPDATE SAMPLE SET PVALUE=101 WHERE PNAME=identity
UPDATE SAMPLE SET PVALUE=201 WHERE PNAME=size
UPDATE SAMPLE SET PVALUE=/tmp/log WHERE PNAME=logloc
UPDATE SAMPLE SET PVALUE=xyz.dev.cloud WHERE PNAME=host

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM