我有以下变量尝试在python中生成一个自动生成SQL语句
_SQL_fields = ("ID", "NAME", "BIRTH", "SEX", "AGE")
_add_SQL_desc_type = ("PRIMARY KEY AUTOINCREASEMENT",)
_SQL_type = ("INT",'TEXT')
_Value = (1,'TOM',19700101,'M',40)
bop = ["AND"] * (len(_SQL_fields) - 1)
mop = ["="] * 5
comma = [","] * 4
exception_field = ["NAME", "BIRTH"]
为了成功设计一个SQL语句,我需要在上面变量生成的字符串下面:
'(ID, NAME, BIRTH, SEX, AGE)'
'(ID PRIMARY KEY AUTOINCREASEMENT INT, NAME TEXT, BIRTH, SEX, AGE)'
'ID = 1 AND NAME = "TOM" AND BIRTH = "19700101" AND SEX = "M" AND AGE = '40''
并删除了exception_field字符串可能看起来像
'(ID, SEX, AGE)'
'(ID PRIMARY KEY AUTOINCREASEMENT INT, SEX, AGE)'
'ID = 1 AND SEX = "M" AND AGE = '40''
==========
到目前为止,我使用类似
的内容str(zip(_SQL_fields,_add_SQL_desc_type,_SQL_type,comma))
或使用
", ".join(_SQL_fields)
得到一个。
但是在处理“逗号”和“引号”时特别麻烦。
'(ID, NAME, BIRTH, SEX, AGE)' <===== this is OK for SQL
'(ID, NAME, BIRTH, SEX, AGE,)' <===== this is NOT
和这个
'ID = 1 AND NAME = "TOM" AND BIRTH = "19700101" AND SEX = "M" and AGE = '40'
^-some var need quotes and some do no need them.
所以任何人都可以分享我如何编写一个干净的代码来生成上面的字符串?
谢谢你的时间!
KC
答案 0 :(得分:0)
获取
'(ID PRIMARY KEY AUTOINCREASEMENT INT, NAME TEXT, BIRTH, SEX, AGE)'
你可以在python中使用itertools模块中的izip_longest。
然后,要删除获取列表中的exception_fields,可以使用set或list comprehension。
l1 = [1, 2, 3, 4]
l2 = [2, 3]
l3 = list(set(l1) - set(l2))
print l3
--> [1, 4]
l3 = [val for val in l1 if val not in l2]
print l3
--> [1, 4]
我推荐列表理解。
", ".join(_SQL_fields)
非常适合获得
'ID, NAME, BIRTH, SEX, AGE'
所以我真的不明白你的问题。