列と値をハードコードすることなくupdate
ステートメントを生成するメソッドを作成したいとします。この文にはオプションのwhere
句が含まれ、executemany
に渡されます。この句には列と値のみが含まれ、そこにはselect
はありません。例:ステートメントをハードコーディングせずにupdate where節でnullを処理する
update TABLE
set
Col1 = 'a',
Col2 = 'b',
Col3 = 'c'
where
Col4 = 'd'
and Col5 = 'e'
and Col1 is null;
私がこれまでに書いた何を:今
def update(self, table_name, update_columns, values, where_columns=None, where=True):
update_columns_and_values = self.generator.generateColumnsAndPlaceholders(update_columns)
if where:
where_clause = self.generator.generateWhereClause(where_columns)
else:
where_clause = ''
query = '''
update {t}
set
{cv}
{w}
'''.format(t=table_name, cv=update_columns_and_values, w=where_clause)
self.cursor.executemany(query, values)
self.connection.commit()
def generateColumnsAndPlaceholders(columns):
if type(columns) is str:
columns = columns.split(', ')
return ', \n'.join([str(c) + ' = ' + "'%s'" for c in columns])
、どのように私は、任意の数の列を取り、ヌルの両方ではないために調整プレースホルダwhere
句を返す関数generateWhereClause
を書く必要があります値(=
と表示されます)とヌル値(is null
と表示されます)? また、の場合、プレースホルダの周りに一重引用符があるため、generateColumnsAndPlaceholders
によって返された文字列が準備されていないと思います。もしそうなら、どうすれば変更できますか?
通常、特定のステートメントをハードコードせずに、更新ステートメントでnull
をどのように扱いますか?