python - 使用 json 对象形成 sql 命令失败
问题描述
我正在尝试使用可以由 python 脚本运行的 json 对象创建 sql 命令。我想出了下面的脚本。func1() 方法有效,但不可读。func2() 是我的目标,但它失败了。有没有简单的方法?
我正在使用python3.4。
#!/usr/bin/env python3
def func1():
url = "http://example.com:9000"
user = "apple"
password = "orange"
kvp = '{"host": "' + url + '"' + ', "user: "' + user + '"}'
sqlCmd1 = '"INSERT INTO hosts (config_info) VALUES(' + kvp + ');"'
print("sqlcmd1:", sqlCmd1)
def func2():
url = "http://example.com:9000"
user = "apple"
password = "orange"
sqlCmd2 = 'INSERT INTO hosts (config_info) VALUES ({"host": "{0}"});'.format(url)
print("sqlCmd2: ", sqlCmd2)
if __name__ == '__main__':
func1()
func2()
sqlcmd1: "INSERT INTO hosts (config_info) VALUES({"host": "http://example.com:9000", "user: "apple"});"
Traceback (most recent call last):
File "./sql.py", line 20, in <module>
func2()
File "./sql.py", line 15, in func2
sqlCmd2 = 'INSERT INTO hosts (config_info) VALUES ({"host": "{0}"});'.format(url)
KeyError: '"host"'
下面的代码有效。
def func2():
url = "http://example.com:9000"
user = "apple"
password = "orange"
sqlCmd2 = 'INSERT INTO hosts (config_info) VALUES ({{"host": "{0}", "user": "{1}","password": "{2}"}});'.format(url, user, password)
print("sqlCmd2: ", sqlCmd2)
解决方案
推荐阅读
- doctrine-orm - 学说 loadClassMetadata
- javascript - 按孩子的孩子排序数组
- imagemagick - 如何配置 imagick 以使用 gpu 支持?
- swift - 三元运算中的“表达式类型'Bool'在没有更多上下文的情况下是模棱两可的”
- postgresql - QueryDSL GroupBy 和 Sum
- excel - HTTPS Post 使用带有 XML 正文和请求标头的 Excel VBA 问题
- android - 调用需要 API 级别 23(当前最低为 18):android.app.Activity#requestPermissions
- microsoft-graph-api - 使用 Graph 查询所有团队
- python - 如何转换通过 model.flow_from_directory 定向的图像尺寸?
- android - BLE 5 外围设备未在支持 BLE 5 的 Android 手机和 iPhone 上得到扫描