2

I am importing data from MS-Excel to PostgreSQL in python(2.6) using pyodbc.

The problem faced is:

There are characters like left single quotation mark(ANSI hex code : 0x91), etc in the excel source. Now, when it is import into PostgreSQL using pyodbc, it terminates and gives the error DatabaseError: invalid byte sequence for encoding "UTF8": 0x91.

What I tried: I used decode('unicode_escape') for the time being. But, this cannot be done as this simply removes/escapes the concerned character.

Alternate trial: Decode initially, Unicode everywhere and then Encode later when needed from database. This can also not be done due to the expanse of the project at hand.

Please suggest me some method/procedure/in-built functions to accomplish the task.

2
  • Don't know if this answer your question. But you might find this related answer of some use. Commented Nov 23, 2011 at 8:07
  • Hey, thanx mac for your efforts. I read that and tried using encode('utf-8') but the following error comes up : UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 33: ordinal not in range(128) Commented Nov 23, 2011 at 8:24

1 Answer 1

1

Find out the real encoding of the source document. It might be WIN1251. Either transcode it (for instance with iconv) or set the client_encoding of PostgreSQL accordingly.

If you don't have a setting in pyodbc (which I don't know), you can always issue a plain SQL command:

SET CLIENT_ENCODING TO 'WIN1251';

More in the chapter "Automatic Character Set Conversion Between Server and Client" of the manual.

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

2 Comments

Hey,Erwin. Could we change the already created database's encoding to the required/said encoding?
@SandipAgarwal: No. It is possible to create a new database (based on template0) in the same db cluster with a different encoding, but the encoding must be compatible with your locale settings, which narros it down. Here is a related posting on SO. I am not convinced this would be a good idea to fix your problem.

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.