V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
pppguest3962
V2EX  ›  Python

请教根据嵌套字典,完成组装 SQL 语句的问题。。。

  •  
  •   pppguest3962 · 2018-09-09 18:31:02 +08:00 · 1951 次点击
    这是一个创建于 2049 天前的主题,其中的信息可能已经有所发展或是发生改变。
    StreamData = {
            "D1_RSET":{
                'sqltype':'int',
                'data':'61207'
            },
            "D2_DCK_time":{
                'sqltype': 'DATETIME',
                'data': '2018-9-9'
            },
            "D3_DCK_des":{
                'sqltype': 'varchar(10)',
                'data': 'TestABC'
            },
             "D4_Exp":{
                'sqltype': 'varchar(80)',
                'data': ''
            }
             "D5_stream_seq":{
                'sqltype': 'int',
                'data': '123'
            },
    }
    
    insertoTableRow = ''
    insertoTableCol = ''
    
    insertoTableSqlStr_Prefix = 'INSERT INTO %s (' % (tableName)
    insertoTableSqlStr = ''
    
        for key1, value1 in StreamData.items():
        	#字段字句组装,这一节写不出来,如何在第一层 for 判断出第二层的 data 字段有没有内容? 有内容才把第一层的 key 加入。。。
            insertoTableRow = insertoTableRow + key1 + ',' 
            #第二层 data 字段的组装???
            for key2, value2 in StreamData[key1].items():
                if key2 == ('data'):  #应该判断 data 的 value 有没有内容的。。。。
                    insertoTableCol = insertoTableCol + value + ','
                    
                    
    完成的状态如下:
    
    insertoTableRow = "(" + insertoTableRowSection + ")"
    insertoTableCol = "(" + insertoTableColSection + ")'
    
    #组装完成最后的 sql 语句
    insertoTableSqlStr = 'INSERT INTO %s (' % (tableName) + insertoTableRow + 'value' + insertoTableCol
    
    

    按照这个 StreamData 字典的例子,D4_Exp 是不用操作,因为它是空的。。。 完成组装的 SQL,写不出来。。。。冏。。。。

    请教各位大大出手拉一把啊,谢谢。。。。。。

    7 条回复    2018-09-10 00:53:37 +08:00
    ebingtel
        1
    ebingtel  
       2018-09-09 20:45:21 +08:00
    ……别写了,就算写出来,别人看着也费劲……为啥不把嵌套的 dict 先改成不嵌套的呢?
    pppguest3962
        2
    pppguest3962  
    OP
       2018-09-09 21:23:19 +08:00
    @ebingtel,您说得很有道理,其实我今天上午也是这么想的。前面已经围绕着这个字典做了很多事情,要改也不是没办法改,只是本喵比较强迫症,看看这种情况下,是怎么样一种思路可以达到的呢。。。。^_^
    xpresslink
        3
    xpresslink  
       2018-09-09 21:47:33 +08:00
    弄这个真够蛋疼的,学习一下 sqlalchemy,peewee 之类的 ORM 不就得了,简单点的直接用 Django 的 ORM
    wangyongbo
        4
    wangyongbo  
       2018-09-09 23:05:48 +08:00
    insertoTableSqlStr_Prefix = 'INSERT INTO {tableName} ({colNames}) value ({colValues})'
    colNames = []
    colValues = []

    def f(sqltype="int", data=None, **kwargs):
    if not data:
    return None

    if sqltype == "int":
    return str(data) if data else 'null'

    return "\"{}\"".format(data)

    for col_name, col_value in StreamData.items():
    data = f(**col_value)
    if data is None:
    continue
    colValues.append(data)
    colNames.append(col_name)

    print colValues, colNames

    print insertoTableSqlStr_Prefix.format(tableName='test', colNames=",".join(colNames), colValues=",".join(colValues))

    这样写符合需要吗?

    D4_Exp 是不用操作,因为它是空的. 空字符串和 null 还是不一样。 不一定它是个空字符串,就不需要处理。
    wangyongbo
        5
    wangyongbo  
       2018-09-09 23:06:32 +08:00
    ```

    StreamData = {
    "D1_RSET":{
    'sqltype':'int',
    'data':'61207'
    },
    "D2_DCK_time":{
    'sqltype': 'DATETIME',
    'data': '2018-9-9'
    },
    "D3_DCK_des":{
    'sqltype': 'varchar(10)',
    'data': 'TestABC'
    },
    "D4_Exp":{
    'sqltype': 'varchar(80)',
    'data': ''
    },
    "D5_stream_seq":{
    'sqltype': 'int',
    'data': '123'
    },
    }

    insertoTableSqlStr_Prefix = 'INSERT INTO {tableName} ({colNames}) value ({colValues})'
    colNames = []
    colValues = []

    def f(sqltype="int", data=None, **kwargs):
    if not data:
    return None

    if sqltype == "int":
    return str(data) if data else 'null'

    return "\"{}\"".format(data)

    for col_name, col_value in StreamData.items():
    data = f(**col_value)
    if data is None:
    continue
    colValues.append(data)
    colNames.append(col_name)

    print colValues, colNames

    print insertoTableSqlStr_Prefix.format(tableName='test', colNames=",".join(colNames), colValues=",".join(colValues))


    ```
    reus
        6
    reus  
       2018-09-10 00:16:51 +08:00
    了解过 SQL 注入吗?
    csx163
        7
    csx163  
       2018-09-10 00:53:37 +08:00
    没细看,试试 dataset 库
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2594 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 01:29 · PVG 09:29 · LAX 18:29 · JFK 21:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.