3

I have a database(postgresql) with more than 100 columns and rows. Some cells in the table are empty,I am using python for scripting so None value is placed in empty cells but it shows the following error when I try to insert into table.

"  psycopg2.ProgrammingError: column "none" does not exist"

Am using psycopg2 as python-postgres interface............Any suggestions??

Thanks in advance......

Here is my code:-

list1=[None if str(x)=='nan' else x for x in list1];

cursor.execute("""INSERT INTO table VALUES %s""" %list1;
);
2
  • Python does not need to use ; semicolons. Commented Jan 20, 2014 at 17:27
  • Does list1 hold just one value? Or are you trying to use this for multiple insertions? Commented Jan 20, 2014 at 17:39

1 Answer 1

6

Do not use % string interpolation, use SQL parameters instead. The database adapter can handle None just fine, it just needs translating to NULL, but only when you use SQL parameters will that happen:

list1 = [(None,) if str(x)=='nan' else (x,) for x in list1]

cursor.executemany("""INSERT INTO table VALUES %s""", list1)

I am assuming that you are trying to insert multiple rows here. For that, you should use the cursor.executemany() method and pass in a list of rows to insert; each row is a tuple with one column here.

If list1 is just one value, then use:

param = list1[0]
if str(param) == 'nan':
    param = None

cursor.execute("""INSERT INTO table VALUES %s""", (param,))

which is a little more explicit and readable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.