简体   繁体   English

通过使用python从yaml文件中读取数据来创建sql文件

[英]create sql file by reading data from yaml file using python

I am new to python.我是python的新手。 I have yaml file (config.yaml) which contains data like below.我有包含如下数据的 yaml 文件 (config.yaml)。

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 .我正在寻找 python 脚本来读取上面的 yaml 文件,并为每个名称和值创建带有更新语句的 sql 文件,如下所示。

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 : /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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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