Inserting values in postgres but they are interpreted as column

匆匆过客 提交于 2019-12-13 03:13:45

问题


I am trying to insert some data in my postgres databae like this:

  def insert_row(conn, row)
    attendee = map_row_to_struct(row)

    conn.execute(
      <<-SQL
        INSERT INTO tmp_attendee_import (email, first_name, last_name)
        VALUES("#{attendee.email}", "#{attendee.first_name}", "#{attendee.last_name}");
      SQL
    )
  end

The SQL is evaluated wonderfully as:

INSERT INTO tmp_attendee_import (email, first_name, last_name)
VALUES("myemail@yahoo.com", "Gigel", "Ion");

Yet I get this error:

Failure/Error:
               conn.execute(
                 <<-SQL
                   INSERT INTO tmp_attendee_import (email, first_name, last_name)
                   VALUES("#{attendee.email}", "#{attendee.first_name}", "#{attendee.last_name}");
                 SQL
               )

     ActiveRecord::StatementInvalid:
       PG::UndefinedColumn: ERROR:  column "myemail@yahoo.com" does not exist
       LINE 2:             VALUES("myemail@yahoo.com", "Gigel", "Ion");
                                  ^
       :             INSERT INTO tmp_attendee_import (email, first_name, last_name)
                   VALUES("myemail@yahoo.com", "Gigel", "Ion");

Anyone has any clue ?


回答1:


Postgres manual

A string constant in SQL is an arbitrary sequence of characters bounded by single quotes ('), for example 'This is a string'. To include a single-quote character within a string constant, write two adjacent single quotes, e.g., 'Dianne''s horse'. Note that this is not the same as a double-quote character (").

There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected.

TL;DR: Single quotes for string constants, double quotes for table/column names.

BTW, the way you're choosing for inserting records is vulnerable to sql-injection.



来源:https://stackoverflow.com/questions/51281335/inserting-values-in-postgres-but-they-are-interpreted-as-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!