Psycopg2 doesn't like table names that start with a lower case letter

前端 未结 3 1557
灰色年华
灰色年华 2020-12-19 03:22

I am running ActiveState\'s ActivePython 2.6.5.12 and PostgreSQL 9.0 Beta 1 under Windows XP.

If I create a table with an upper case first letter (i.e. Books), psyco

相关标签:
3条回答
  • 2020-12-19 04:02

    To add to the other answer, the behaviour of Postresql about case-sentivity of identifiers (table names and column names) is :

    • If the name is not quoted, it is converted to lowercase. Otherwise, it's left untouched.
    • Afterwards, a case sensitive match is attempted.

    This applies not only for queries, but also for schema manipulation; in particular: table creation.

    The golden rule is consistency:

    If you want to write portable applications you are advised to always quote a particular name or never quote it

    The posted problem arose, probably, because the tables and columns names were quoted at creation time (hence, they were not converted to lowercase). So, now they must be quoted (and case-sensitive) in all queries.

    Normally, all works as expected.

    db=# create table Xxx (id integer); -- unquoted, will be converted to lowercase
    CREATE TABLE
    db=# select * from xXx;    -- this works ok
    id
    ----
    (0 rows)
    db=# create table "Xxxx" (id integer);  -- will be left untouched
    CREATE TABLE
    db=# select * from xxxx;                -- bad
    ERROR:  relation "xxxx" does not exist
    LINE 1: select * from xxxx;
    db=# select * from Xxxx;                -- bad
    ERROR:  relation "xxxx" does not exist
    LINE 1: select * from Xxxx;
    ^
    db=# select * from "Xxxx";               -- ok
    id
    ----
    (0 rows)
    
    db=# \dt *xx*
    List of relations
    Schema | Name | Type  |  Owner
    --------+------+-------+----------
    public | Xxxx | table | postgres
    public | xxx  | table | postgres
    
    0 讨论(0)
  • 2020-12-19 04:03

    Read "Identifiers and Key Words" from the manual, especially the part about "quoted identifiers".

    0 讨论(0)
  • 2020-12-19 04:22

    I often have to use Psycopg2 with tables that have been created by other people and they use a lot of case mixing in their column names.

    The solution I found is to use

    from psycopg2.extensions import AsIs
    

    and to then put the column name in a variable like:

    column_name = '"Column_Mixed_Case"'#Mind the '" quotes combination !
    

    and pass the variable to the sql as follows

    data = AsIs(column_name)
    sql = "select %s from table"
    cur.execute(sql,data)
    
    0 讨论(0)
提交回复
热议问题