Обсуждение: Encountered an error

Поиск
Список
Период
Сортировка

Encountered an error

От
Shaan Repswal
Дата:
I am trying to insert a new record into my "prototypedb" database. This here below is the section of my code that I am using to access and work on my database.

What I am trying to do here is enter one record (three values) in three columns name, code and type. Then create a new column and then add one value to the new column for the aforementioned already entered record.

cur = conn.cursor()

        #Enter the three value basic record
        cur.execute("""INSERT INTO inventory (name, code, type)
                    VALUES (%s, %s, %s);""", [self.entry_product_name.get_text(), self.new_product_code.get_text(), self.new_product_type.get_text()])

        #Take out list of Text Entry boxes
        #self.quantity_list is a list of two value tuples each of which holds a reference to a text box in my GUI
        for x in self.quantity_list:
            if x[0].get_text() !="" and x[1].get_text() != "":
                #First make the appropriate column
                cur.execute("""ALTER TABLE inventory
                            ADD %s integer DEFAULT NULL;""", [x[0].get_text()])
                #Then give that column the appropriate value for the current record
                cur.execute("""UPDATE inventory
                            SET %s = %s
                            WHERE name = %s;""", [x[0].get_text(), x[1].get_text(), self.entry_product_name.get_text()])
            else:
                continue;

        conn.commit()
        cur.close()
        conn.close()


But Alas! There is an Error!

Traceback (most recent call last):
  File "C:\Python34\prototype_husk.py", line 134, in submit_data
    ADD %s integer DEFAULT NULL;""", [x[0].get_text()])
psycopg2.ProgrammingError: syntax error at or near "'26.2 LTRS'"
LINE 2:                             ADD '26.2 LTRS' integer DEFAULT ...
                                        ^


I have attached herein a screenshot of the values entered. So the error can make more sense.
Вложения

Re: Encountered an error

От
Daniele Varrazzo
Дата:
On Thu, Mar 10, 2016 at 5:37 AM, Shaan Repswal
<shaun.reapswaal@gmail.com> wrote:
>                 #First make the appropriate column
>                 cur.execute("""ALTER TABLE inventory
>                             ADD %s integer DEFAULT NULL;""",
> [x[0].get_text()])
>                 #Then give that column the appropriate value for the current
> record
>                 cur.execute("""UPDATE inventory
>                             SET %s = %s
>                             WHERE name = %s;""", [x[0].get_text(),
> x[1].get_text(), self.entry_product_name.get_text()])

You cannot use %s to pass a table or field name: %s is only used for the values.

There is still no support for escaping values into identifier names.
There is something in the current master: the function
psycopg2.extensions.quote_ident(), but it hasn't been released yet and
the interface may change before the release.

-- Daniele


Re: Encountered an error

От
Adrian Klaver
Дата:
On 03/09/2016 09:37 PM, Shaan Repswal wrote:
> I am trying to insert a new record into my "prototypedb" database. This
> here below is the section of my code that I am using to access and work
> on my database.
>
> What I am trying to do here is enter one record (three values) in three
> columns name, code and type. Then create a new column and then add one
> value to the new column for the aforementioned already entered record.
>
> cur = conn.cursor()
>
>          #Enter the three value basic record
>          cur.execute("""INSERT INTO inventory (name, code, type)
>                      VALUES (%s, %s, %s);""",
> [self.entry_product_name.get_text(), self.new_product_code.get_text(),
> self.new_product_type.get_text()])
>
>          #Take out list of Text Entry boxes
>          #self.quantity_list is a list of two value tuples each of which
> holds a reference to a text box in my GUI
>          for x in self.quantity_list:
>              if x[0].get_text() !="" and x[1].get_text() != "":
>                  #First make the appropriate column
>                  cur.execute("""ALTER TABLE inventory
>                              ADD %s integer DEFAULT NULL;""",
> [x[0].get_text()])
>                  #Then give that column the appropriate value for the
> current record
>                  cur.execute("""UPDATE inventory
>                              SET %s = %s
>                              WHERE name = %s;""", [x[0].get_text(),
> x[1].get_text(), self.entry_product_name.get_text()])
>              else:
>                  continue;
>
>          conn.commit()
>          cur.close()
>          conn.close()
>
>
> But Alas! There is an Error!
>
> Traceback (most recent call last):
>    File "C:\Python34\prototype_husk.py", line 134, in submit_data
>      ADD %s integer DEFAULT NULL;""", [x[0].get_text()])
> psycopg2.ProgrammingError: syntax error at or near "'26.2 LTRS'"
> LINE 2:                             ADD '26.2 LTRS' integer DEFAULT ...
>                                          ^
>

This will not work for the reasons Daniele gave. You have two choices:

1) Build the SQL string using Python string formatting.

2) Do it with the Postgres format(). From a psql session:

test=> select format('ALTER tbl_a ADD %I int DEFAULT NULL', 'fld_2');
                  format
----------------------------------------
  ALTER tbl_a ADD fld_2 int DEFAULT NULL

In psycopg this is a two step process, submit the query and then
resubmit the returned string.

>
> I have attached herein a screenshot of the values entered. So the error
> can make more sense.
>
>
>


--
Adrian Klaver
adrian.klaver@aklaver.com


Re: Encountered an error

От
Karsten Hilbert
Дата:
On Thu, Mar 10, 2016 at 05:02:51AM -0800, Adrian Klaver wrote:

>>                 #First make the appropriate column

> This will not work for the reasons Daniele gave. You have two choices:
>
> 1) Build the SQL string using Python string formatting.
>
> 2) Do it with the Postgres format(). From a psql session:
>
> test=> select format('ALTER tbl_a ADD %I int DEFAULT NULL', 'fld_2');
>                  format
> ----------------------------------------
>  ALTER tbl_a ADD fld_2 int DEFAULT NULL
>
> In psycopg this is a two step process, submit the query and then resubmit
> the returned string.

While this is a nice solution to OPs problem I cannot resist
the urge to point out that to me the whole approach of adding
a column from within client code (outside a database
management application) does have at least a whiff of design
smell to it.

There's probably better ways to implement EAV. Approaches
with JSON, hstore, xml, or the venerable
CREATE TABLE inventory_detail(pk, fk_inventory, detail_name, detail_value)
come to mind.

Regards,
Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


Re: Encountered an error

От
Karsten Hilbert
Дата:
On Thu, Mar 10, 2016 at 03:30:14PM +0100, Karsten Hilbert wrote:

> While this is a nice solution to OPs problem I cannot resist
> the urge to point out that to me the whole approach of adding
> a column from within client code (outside a database
> management application) does have at least a whiff of design
> smell to it.

Like, what happens if the user enters something to be used as
a column name which isn't suitable for an identifier ?

And then what if two different unsuitable user input values
get normalized into the same column-name-suitable version ?

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


Re: Encountered an error

От
Shaan Repswal
Дата:
I am new to databases and am a novice to programming in general. But I have a problem and this is the only way it seems to me it will work. I plan on learning the rest later. After I've created this program. To give you guys an idea of how naive I am. Please know that a lot of this just went over my head.

@Daniele if I can't use %s what can I use? The "%l" that Adrian suggested?
@Daniele What do you mean escaping values into identifier names?

@Adrian - I am Python string formatting? Whatt kind of string formatting. Which query should I format? The "Add a new column" query or the "add a value to the column of the currently entered record" query located right after it.
@Adrian - I don't think I understand what you mean by the example of the format() function. Am I supposed to use it in psql? But my program is in Python... Is there some manual where I could get more info on this and where I could see a few examples of this function?

@Karsten - I know, I got the feeling that the design felt awry as well. The database will be on the local machine. And the client side will have the code to error check the column names being added and also if there already is a column by this name or not.



On Thu, Mar 10, 2016 at 8:02 PM, Karsten Hilbert <Karsten.Hilbert@gmx.net> wrote:
On Thu, Mar 10, 2016 at 03:30:14PM +0100, Karsten Hilbert wrote:

> While this is a nice solution to OPs problem I cannot resist
> the urge to point out that to me the whole approach of adding
> a column from within client code (outside a database
> management application) does have at least a whiff of design
> smell to it.

Like, what happens if the user enters something to be used as
a column name which isn't suitable for an identifier ?

And then what if two different unsuitable user input values
get normalized into the same column-name-suitable version ?

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


--
Sent via psycopg mailing list (psycopg@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/psycopg

Re: Encountered an error

От
Adrian Klaver
Дата:
On 03/10/2016 11:46 AM, Shaan Repswal wrote:
> I am new to databases and am a novice to programming in general. But I
> have a problem and this is the only way it seems to me it will work. I
> plan on learning the rest later. After I've created this program. To
> give you guys an idea of how naive I am. Please know that a lot of this
> just went over my head.
>
> @Daniele if I can't use %s what can I use? The "%l" that Adrian suggested?

They come from different systems, the %s from Python string formatting,
the %I from Postgres formatting, so they cannot be mixed. This is not
strictly true as Postgres also uses %s. See below for respective docs(I
am using Python 2 docs):

Python
https://docs.python.org/2/library/stdtypes.html#string-formatting

Postgres
http://www.postgresql.org/docs/9.5/interactive/functions-string.html#FUNCTIONS-STRING-FORMAT

> @Daniele What do you mean escaping values into identifier names?

See here:

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

>
> @Adrian - I am Python string formatting? Whatt kind of string
> formatting. Which query should I format? The "Add a new column" query or
> the "add a value to the column of the currently entered record" query
> located right after it.

See the above Python string formatting section on how to build a string.
Build it and then pass that to your cursor to execute.

> @Adrian - I don't think I understand what you mean by the example of the
> format() function. Am I supposed to use it in psql? But my program is in
> Python... Is there some manual where I could get more info on this and
> where I could see a few examples of this function?

No I was showing an example in psql as it was quick and easy. You can
just build the string something like this(not tested)

cur.execute("select format('ALTER tbl_a ADD %I int DEFAULT NULL', 'fld_2')")

query_str = cur.fetchone()[0]

query_str should be the built string that you could then execute:

cur.execute(query_str)

For examples see the Postgres link above.

Also a previous thread on this list, starting here:

http://www.postgresql.org/message-id/554B69A9.2070209@aklaver.com

>
> @Karsten - I know, I got the feeling that the design felt awry as well.
> The database will be on the local machine. And the client side will have
> the code to error check the column names being added and also if there
> already is a column by this name or not.
>
>
>
> On Thu, Mar 10, 2016 at 8:02 PM, Karsten Hilbert
> <Karsten.Hilbert@gmx.net <mailto:Karsten.Hilbert@gmx.net>> wrote:
>
>     On Thu, Mar 10, 2016 at 03:30:14PM +0100, Karsten Hilbert wrote:
>
>     > While this is a nice solution to OPs problem I cannot resist
>     > the urge to point out that to me the whole approach of adding
>     > a column from within client code (outside a database
>     > management application) does have at least a whiff of design
>     > smell to it.
>
>     Like, what happens if the user enters something to be used as
>     a column name which isn't suitable for an identifier ?
>
>     And then what if two different unsuitable user input values
>     get normalized into the same column-name-suitable version ?
>
>     Karsten
>     --
>     GPG key ID E4071346 @ eu.pool.sks-keyservers.net
>     <http://eu.pool.sks-keyservers.net>
>     E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346
>
>
>     --
>     Sent via psycopg mailing list (psycopg@postgresql.org
>     <mailto:psycopg@postgresql.org>)
>     To make changes to your subscription:
>     http://www.postgresql.org/mailpref/psycopg
>
>


--
Adrian Klaver
adrian.klaver@aklaver.com


Re: Encountered an error

От
Karsten Hilbert
Дата:
On Fri, Mar 11, 2016 at 01:16:33AM +0530, Shaan Repswal wrote:

> I am new to databases and am a novice to programming in general.

Don't worry.

> @Karsten - I know, I got the feeling that the design felt awry as well. The
> database will be on the local machine. And the client side will have the
> code to error check the column names being added and also if there already
> is a column by this name or not.

You can add a second table (pseudo code)

    inventory_detail
        pk serial primary key
        fk_inventory integer foreign key (inventory.pk)
        detail_name text
        detail_value text

and then - instead of creating columns in table inventory -
add rows to the inventory_detail table where .detail_name
would hold what otherwise would be the column name of the new
column in inventory and .detail_value the value you would
have put into the new column in table inventory. The
fk_inventory column would hold the primary key of the row in
the inventory table this inventory_detail row belongs to.

Just a suggestion.

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


Re: Encountered an error

От
Shaan Repswal
Дата:
Hey guys I built the string in python and then passed it to the cur.execute() function. This was so simple! It scares me to see that I didn't get it the first time around. But anyway, thanks for laying to rest my confusions. Thank you so much!

On Fri, Mar 11, 2016 at 3:33 AM, Karsten Hilbert <Karsten.Hilbert@gmx.net> wrote:
On Fri, Mar 11, 2016 at 01:16:33AM +0530, Shaan Repswal wrote:

> I am new to databases and am a novice to programming in general.

Don't worry.

> @Karsten - I know, I got the feeling that the design felt awry as well. The
> database will be on the local machine. And the client side will have the
> code to error check the column names being added and also if there already
> is a column by this name or not.

You can add a second table (pseudo code)

        inventory_detail
                pk serial primary key
                fk_inventory integer foreign key (inventory.pk)
                detail_name text
                detail_value text

and then - instead of creating columns in table inventory -
add rows to the inventory_detail table where .detail_name
would hold what otherwise would be the column name of the new
column in inventory and .detail_value the value you would
have put into the new column in table inventory. The
fk_inventory column would hold the primary key of the row in
the inventory table this inventory_detail row belongs to.

Just a suggestion.

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


--
Sent via psycopg mailing list (psycopg@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/psycopg

Re: Encountered an error

От
Shaan Repswal
Дата:
I tried to format the strings the Python way but... I'm getting this error:-

Traceback (most recent call last):
  File "C:\Python34\prototype_husk.py", line 133, in submit_data
    cur.execute(add_column)
psycopg2.ProgrammingError: syntax error at or near "26.2"
LINE 2:                             ADD 26.2 LTRS int DEFAULT NULL

Here is my code:-

    def submit_data(self, whatevs):
        conn = psycopg2.connect("dbname=prototypedb user=postgres password=superman123")
        cur = conn.cursor()

        cur.execute("""INSERT INTO inventory (name, code, type)
                    VALUES (%s, %s, %s);""", [self.entry_product_name.get_text(), self.new_product_code.get_text(), self.new_product_type.get_text()])

        for x in self.quantity_list:
            if x[0].get_text() !="" and x[1].get_text() != "":
                add_column = """ALTER TABLE inventory
                            ADD %s int DEFAULT NULL""" % x[0].get_text()
                cur.execute(add_column)
                add_details = """UPDATE inventory
                            SET %s = %s
                            WHERE name = %s;""" % (x[0].get_text(), x[1].get_text(), self.entry_product_name.get_text())
                cur.execute(add_details)
            else:
                continue;

        conn.commit()
        cur.close()
        conn.close()

On Mon, Mar 14, 2016 at 7:41 PM, Shaan Repswal <shaun.reapswaal@gmail.com> wrote:
Hey guys I built the string in python and then passed it to the cur.execute() function. This was so simple! It scares me to see that I didn't get it the first time around. But anyway, thanks for laying to rest my confusions. Thank you so much!

On Fri, Mar 11, 2016 at 3:33 AM, Karsten Hilbert <Karsten.Hilbert@gmx.net> wrote:
On Fri, Mar 11, 2016 at 01:16:33AM +0530, Shaan Repswal wrote:

> I am new to databases and am a novice to programming in general.

Don't worry.

> @Karsten - I know, I got the feeling that the design felt awry as well. The
> database will be on the local machine. And the client side will have the
> code to error check the column names being added and also if there already
> is a column by this name or not.

You can add a second table (pseudo code)

        inventory_detail
                pk serial primary key
                fk_inventory integer foreign key (inventory.pk)
                detail_name text
                detail_value text

and then - instead of creating columns in table inventory -
add rows to the inventory_detail table where .detail_name
would hold what otherwise would be the column name of the new
column in inventory and .detail_value the value you would
have put into the new column in table inventory. The
fk_inventory column would hold the primary key of the row in
the inventory table this inventory_detail row belongs to.

Just a suggestion.

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


--
Sent via psycopg mailing list (psycopg@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/psycopg


Re: Encountered an error

От
Jonathan Rogers
Дата:
Did you mean to add a column called "26.2 LTRS"? SQL identifiers with
embedded spaces must always be enclosed in quotes.

Please don't use Python string formatting to interpolate values in your
SQL UPDATE statement since that invites SQL injection vulnerabilities.
Here's the psycopg2 documentation about using it to interpolate values
safely:

http://pythonhosted.org/psycopg2/usage.html#passing-parameters-to-sql-queries

On 03/14/2016 11:11 AM, Shaan Repswal wrote:
> I tried to format the strings the Python way but... I'm getting this error:-
>
> Traceback (most recent call last):
>   File "C:\Python34\prototype_husk.py", line 133, in submit_data
>     cur.execute(add_column)
> psycopg2.ProgrammingError: syntax error at or near "26.2"
> LINE 2:                             ADD 26.2 LTRS int DEFAULT NULL
>
> Here is my code:-
>
>     def submit_data(self, whatevs):
>         conn = psycopg2.connect("dbname=prototypedb user=postgres
> password=superman123")
>         cur = conn.cursor()
>
>         cur.execute("""INSERT INTO inventory (name, code, type)
>                     VALUES (%s, %s, %s);""",
> [self.entry_product_name.get_text(), self.new_product_code.get_text(),
> self.new_product_type.get_text()])
>
>         for x in self.quantity_list:
>             if x[0].get_text() !="" and x[1].get_text() != "":
>                 add_column = """ALTER TABLE inventory
>                             ADD %s int DEFAULT NULL""" % x[0].get_text()
>                 cur.execute(add_column)
>                 add_details = """UPDATE inventory
>                             SET %s = %s
>                             WHERE name = %s;""" % (x[0].get_text(),
> x[1].get_text(), self.entry_product_name.get_text())
>                 cur.execute(add_details)
>             else:
>                 continue;
>
>         conn.commit()
>         cur.close()
>         conn.close()
>
> On Mon, Mar 14, 2016 at 7:41 PM, Shaan Repswal
> <shaun.reapswaal@gmail.com <mailto:shaun.reapswaal@gmail.com>> wrote:
>
>     Hey guys I built the string in python and then passed it to the
>     cur.execute() function. This was so simple! It scares me to see that
>     I didn't get it the first time around. But anyway, thanks for laying
>     to rest my confusions. Thank you so much!
>
>     On Fri, Mar 11, 2016 at 3:33 AM, Karsten Hilbert
>     <Karsten.Hilbert@gmx.net <mailto:Karsten.Hilbert@gmx.net>> wrote:
>
>         On Fri, Mar 11, 2016 at 01:16:33AM +0530, Shaan Repswal wrote:
>
>         > I am new to databases and am a novice to programming in general.
>
>         Don't worry.
>
>         > @Karsten - I know, I got the feeling that the design felt awry as well. The
>         > database will be on the local machine. And the client side will have the
>         > code to error check the column names being added and also if there already
>         > is a column by this name or not.
>
>         You can add a second table (pseudo code)
>
>                 inventory_detail
>                         pk serial primary key
>                         fk_inventory integer foreign key (inventory.pk
>         <http://inventory.pk>)
>                         detail_name text
>                         detail_value text
>
>         and then - instead of creating columns in table inventory -
>         add rows to the inventory_detail table where .detail_name
>         would hold what otherwise would be the column name of the new
>         column in inventory and .detail_value the value you would
>         have put into the new column in table inventory. The
>         fk_inventory column would hold the primary key of the row in
>         the inventory table this inventory_detail row belongs to.
>
>         Just a suggestion.
>
>         Karsten
>         --
>         GPG key ID E4071346 @ eu.pool.sks-keyservers.net
>         <http://eu.pool.sks-keyservers.net>
>         E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346
>
>
>         --
>         Sent via psycopg mailing list (psycopg@postgresql.org
>         <mailto:psycopg@postgresql.org>)
>         To make changes to your subscription:
>         http://www.postgresql.org/mailpref/psycopg
>
>
>


--
Jonathan Rogers
Socialserve.com by Emphasys Software
jrogers@emphasys-software.com


Re: Encountered an error

От
Karsten Hilbert
Дата:
On Mon, Mar 14, 2016 at 08:41:04PM +0530, Shaan Repswal wrote:

> I tried to format the strings the Python way but... I'm getting this error:-
>
> Traceback (most recent call last):
>   File "C:\Python34\prototype_husk.py", line 133, in submit_data
>     cur.execute(add_column)
> psycopg2.ProgrammingError: syntax error at or near "26.2"
> LINE 2:                             ADD 26.2 LTRS int DEFAULT NULL

That is what I have been trying to point out - you can't add
a column named "25.2 LTRS" even if the user entered that
value. You will need code to sanitize user input to become
suitable for column names. I seem to remember you saying you
already have such code ?

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


Re: Encountered an error

От
Shaan Repswal
Дата:
The value of the textbox is in String. I just have to call a "get_text()" method on a textbox object and I get the string value. I used it just a few minutes ago. It's working now. Thanks a lot. I'm not too worried about sql injections just yet because the only people about to use this application are supposed to have all access anyway.

On Tue, Mar 15, 2016 at 12:00 AM, Karsten Hilbert <Karsten.Hilbert@gmx.net> wrote:
On Mon, Mar 14, 2016 at 08:41:04PM +0530, Shaan Repswal wrote:

> I tried to format the strings the Python way but... I'm getting this error:-
>
> Traceback (most recent call last):
>   File "C:\Python34\prototype_husk.py", line 133, in submit_data
>     cur.execute(add_column)
> psycopg2.ProgrammingError: syntax error at or near "26.2"
> LINE 2:                             ADD 26.2 LTRS int DEFAULT NULL

That is what I have been trying to point out - you can't add
a column named "25.2 LTRS" even if the user entered that
value. You will need code to sanitize user input to become
suitable for column names. I seem to remember you saying you
already have such code ?

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346


--
Sent via psycopg mailing list (psycopg@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/psycopg

Re: Encountered an error

От
Jonathan Rogers
Дата:
On 03/15/2016 01:15 AM, Shaan Repswal wrote:
> The value of the textbox is in String. I just have to call a
> "get_text()" method on a textbox object and I get the string value. I
> used it just a few minutes ago. It's working now. Thanks a lot. I'm not
> too worried about sql injections just yet because the only people about
> to use this application are supposed to have all access anyway.

That attitude is exactly why security flaws are so rampant. How likely
is it that you'll rewrite all your queries the day someone untrusted
gains access to the system? Several classes of bugs are eliminated by
using the DB API correctly, not just security vulnerabilities. Use
psycopg2's value interpolation now or you'll regret it later.

I just fixed a bug in which Postgres received invalid syntax because
Python code sent a value for an interval as an exponential
notation-formatted float. The code would work as long as the the value
wasn't below some threshold so the bug lurked for months. The fix was to
use a Python timedelta value, which psycopg2 always sends to Postgres
correctly as an interval.

You don't have to take my word for it. Read the docs themselves about
the pitfalls of doing your own SQL value formatting:

http://initd.org/psycopg/docs/usage.html#sql-injection
--
Jonathan Rogers
Socialserve.com by Emphasys Software
jrogers@emphasys-software.com


Re: Encountered an error

От
Jonathan Rogers
Дата:
On 03/10/2016 12:37 AM, Shaan Repswal wrote:
> I am trying to insert a new record into my "prototypedb" database. This
> here below is the section of my code that I am using to access and work
> on my database.
>
> What I am trying to do here is enter one record (three values) in three
> columns name, code and type. Then create a new column and then add one
> value to the new column for the aforementioned already entered record.
>
> cur = conn.cursor()
>
>         #Enter the three value basic record
>         cur.execute("""INSERT INTO inventory (name, code, type)
>                     VALUES (%s, %s, %s);""",
> [self.entry_product_name.get_text(), self.new_product_code.get_text(),
> self.new_product_type.get_text()])
>
>         #Take out list of Text Entry boxes
>         #self.quantity_list is a list of two value tuples each of which
> holds a reference to a text box in my GUI
>         for x in self.quantity_list:
>             if x[0].get_text() !="" and x[1].get_text() != "":
>                 #First make the appropriate column
>                 cur.execute("""ALTER TABLE inventory
>                             ADD %s integer DEFAULT NULL;""",
> [x[0].get_text()])
>                 #Then give that column the appropriate value for the
> current record
>                 cur.execute("""UPDATE inventory
>                             SET %s = %s
>                             WHERE name = %s;""", [x[0].get_text(),
> x[1].get_text(), self.entry_product_name.get_text()])
>             else:
>                 continue;
>
>         conn.commit()
>         cur.close()
>         conn.close()
>
>
> But Alas! There is an Error!
>
> Traceback (most recent call last):
>   File "C:\Python34\prototype_husk.py", line 134, in submit_data
>     ADD %s integer DEFAULT NULL;""", [x[0].get_text()])
> psycopg2.ProgrammingError: syntax error at or near "'26.2 LTRS'"
> LINE 2:                             ADD '26.2 LTRS' integer DEFAULT ...
>                                         ^
>

I'm having a very hard time imagining why it would ever make sense to
have a column called "26.2 LTRS", though Postgres will allow it. That
string represents a quantity in liters, correct? In that case, you
almost certainly want a column called something like "volume_in_liters"
into which you can insert the value "26.2".

--
Jonathan Rogers
Socialserve.com by Emphasys Software
jrogers@emphasys-software.com


Re: Encountered an error

От
Karsten Hilbert
Дата:
On Tue, Mar 15, 2016 at 10:45:32AM +0530, Shaan Repswal wrote:

> The value of the textbox is in String. I just have to call a "get_text()"
> method on a textbox object and I get the string value. I used it just a few
> minutes ago. It's working now. Thanks a lot. I'm not too worried about sql
> injections just yet because the only people about to use this application
> are supposed to have all access anyway.

This is not at all about SQL injections. If I understand
correctly you are attempting to use a user supplied string
for a column name in a table.

In this case you will _have_ to preprocess the user input to
make it even _suitable_ for becoming a column name. At that
point not a single thought has been spent on any security
implications of such an approach yet.

Karsten
--
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346