sqlalchemypyodbcturbogears2

sqlalchemy throws a DataError 22001 using tg2 and pyodbc to write into SQL Server 2005


I'm using a reflected sqlalchemy mapped class into a SQL Server table. I DBSession.add() instances of Activities class (the mapped class) with data I get from a different source. and then I called transaction.commit() (since I'm calling from tg2 I can't use session.commit())

the error traceback:

DataError: (DataError) ('22001', '[22001] [Microsoft][ODBC SQL Server Driver][SQ
L Server]String or binary data would be truncated. (8152) (SQLExecDirectW); [010
00] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been termin
ated. (3621)') u'INSERT INTO [NOAR_LOADEVENTS] ([EVENTCODE]) VALUES (?)' ((u'210
401',), (u'210402',), (u'210602',), (u'210603',), (u'000010',), (u'000102',), (u
'000206',), (u'000107',)  ... displaying 10 of 49 total bound parameter sets ...
  (u'211302',), (u'210403',))

be glad to any help about this since I'm clueless how to continue/debug this from here

edit: I had a suspicion that this has something to do with unicode so I changed the sqlalchemy column to unicode.

maybe the DataError is stuck somehow and I need to call a rollback, but I don't know hot to call a rollback in transaction in tg2

edit:the EVENTCODE column in the mssql is:datatype:PK,nvarchar(6), not null hope this helps

another edit: the insert code (the relevant part)

event = #json with data
ac['EVENTCODE']=event.get('code')#for example u'210602' - from the failing data
...
...
e = Activities(**ac) # this is the class mapped with sqlalchemy to the NOAR_LOADEVENTS in sqlalchemy.
DBSession2.add(e)
transaction.commit()

Solution

  • solved. @beargle comment led me in the right direction. seems the problem strangly enough was trying to insert to nvarchar field with length of 6. seems that a unicode string with a length of 6 like: u'110110' would produce an error while a string '110110' passes fine. so i use

    variable.encode('utf-8') and everything work.

    what ever.