SQLAlchemy error: "Argument formats cannot be mixed" when entering variables

I have a Python script that runs a pgSQL file through the SQLAlchemy connection.execute function. Here's the code block in Python:

results = pg_conn.execute(sql_cmd, beg_date = datetime.date(2015,4,1), end_date = datetime.date(2015,4,30))

And here is one of the areas where a variable is introduced into my SQL:

WHERE
    (   dv.date >= %(beg_date)s AND
        dv.date <= %(end_date)s)

When I run this, I get a cryptic python error:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) argument formats can't be mixed

... followed by a huge dump of abusive SQL query. I ran this exact code with the same legend. Why doesn't it work this time?

+4
source share
2 answers

As it turned out, I used the SQL LIKE statement in the new SQL query, and the% operand was messing around with the Python escaping capabilities. For instance:

    dv.device LIKE 'iPhone%' or
    dv.device LIKE '%Phone'

, , , . pgSQL SQL-. :

        dv.device ~ E'iPhone.*' or
        dv.device ~ E'.*Phone$'

, : LIKE- regex '~', . , . ( .)

+4

, Nikhil. LIKE, , , , :

DatabaseError: Execution failed on sql '...': argument formats can't be mixed

, LIKE. , psycopg2 LIKE. , % %%. , :

SELECT *
FROM people
WHERE start_date > %(beg_date)s
AND name LIKE 'John%';

:

SELECT *
FROM people
WHERE start_date > %(beg_date)s
AND name LIKE 'John%%';

pscopg2: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

+2

Source: https://habr.com/ru/post/1589060/


All Articles