在psycopg2

时间:2019-05-27 19:50:49

标签: python-3.x postgresql functional-programming sql-update psycopg2

我创建了一个微型功能管道,该管道使用regex创建了一条更新语句,然后将该语句和数据传递给pycopg2来执行。

如果我将语句粘贴粘贴到循环外,它将起作用,如果我尝试循环所有语句,则会收到错误消息。

# Function to create statement


def psycopg2_regex_replace_chars(table, col, regex_chars_old, char_new):
    query = "UPDATE {} SET {} = regexp_replace({}, %s , %s, 'g');".format(table, col, col)
    data = (regex_chars_old, char_new)
    return (query, data)


# Create functions with intelligible names


replace_separators_with_space = partial(psycopg2_regex_replace_chars,regex_chars_old='[.,/[-]]',char_new=' ')
replace_amper_with_and = partial(psycopg2_regex_replace_chars, regex_chars_old='&', char_new='and')


# create funcs_list


funcs_edit = [replace_separators_with_space,
              replace_amper_with_and]

到目前为止,太好了。

这有效

stmt = "UPDATE persons SET name = regexp_replace(name, %s , %s, 'g');"
data = ('[^a-zA-z0-9]', ' ')
cur.execute(stmt, data)
conn.commit()

失败

tables = ["persons"]
cols = ["name", "dob"]

for table in tables:
   for col in cols:
        for func in funcs_edit:
            query, data = func(table=table, col=col)
            cur.execute(query, data)
            conn.commit()

错误

<ipython-input-92-c8ba5d469f88> in <module>
      6         for func in funcs_edit:
      7             query, data = func(table=table, col=col)
----> 8             cur.execute(query, data)
      9             conn.commit()

ProgrammingError: function regexp_replace(date, unknown, unknown, unknown) does not exist
LINE 1: UPDATE persons SET dob = regexp_replace(dob, '[.,/[-]]' , ' ...
                                 ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.```

0 个答案:

没有答案