views:

46

answers:

1

Hi ALL,

I have below variables try to make an auto generating SQL statement in python

_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"]

for successful design a SQL statement I need below strings generated by above variable:

'(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''

and removed exception_field strings may looks like

'(ID, SEX, AGE)'
'(ID PRIMARY KEY AUTOINCREASEMENT INT, SEX, AGE)'
'ID = 1 AND SEX = "M" AND AGE = '40''

==========

so far I use something like

str(zip(_SQL_fields,_add_SQL_desc_type,_SQL_type,comma)) 

or using

", ".join(_SQL_fields) 

to get one.

but I get a lot of mess when, especiall in processing the "comma" and "quotes".

'(ID, NAME, BIRTH, SEX, AGE)'    <===== this is OK for SQL
'(ID, NAME, BIRTH, SEX, AGE,)'    <===== this is NOT

and this

'ID = 1 AND NAME = "TOM" AND BIRTH = "19700101" AND SEX = "M" and AGE = '40'  
                   ^-some var need quotes and some do no need them.

So anyone can share me how to write a clean code for generate above strings?

Thanks for your time!

KC

+1  A: 

To obtain

'(ID PRIMARY KEY AUTOINCREASEMENT INT, NAME TEXT, BIRTH, SEX, AGE)'

you can use izip_longest from itertools module in python.

Then, to remove exception_fields in the obtain list, you can use set or 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]

I recommend the list comprehension.

", ".join(_SQL_fields) 

is perfect to obtain

'ID, NAME, BIRTH, SEX, AGE'

so i don't really understand you're problem.

ohe
thanks ohe. my problem can be solved by the ORM : SQLAlchemy now.
K. C