3

I'm trying to read from a file and insert the data to a postgresql table in python using the psycopg2.

Here's the function I wrote:

def insert(file, table, col, conn):
    sql = "INSERT INTO "+table+"("+col+") VALUES(%s)"
    cur = conn.cursor()
    with open(os.path.join(DEFAULTS_FOLDER, file)) as fp:
        line = fp.readline()
        while line:
            cur.execute(sql, (line.rstrip(),))
            line = fp.readline()
        conn.commit()
        cur.close()
    return

For some reason I get an error:

cur.execute(sql, (line.rstrip(),)) psycopg2.DataError: malformed array literal: "hello" LINE 1: INSERT INTO greetings(gname) VALUES('hello')

I also tried to insert a plain string and I still get the same error.

1

1 Answer 1

5

The error message means that the column gname of the table greetings is an array, not a plain text. If it is a text array, the query should look like this:

INSERT INTO greetings(gname) VALUES('{hello}')

You should change the relevant fragment of your code, e.g.:

cur.execute(sql, ("{{{}}}".format(line.rstrip()),))
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it was because my column was of type char[]. Thanks!

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.