Reputation: 6285
I have a MySQL table where a field have a type of INT. In my Python script I am reading the hexadecimal value (0xc558, for example) and trying to insert this value in the table as INT field type.
Doing so gives me:
(1265, "Data truncated for column at row 1
)
An INT field type should be a standard integer with 4 bytes which should accept the value of 0xC558, which is 50520 in a decimal world.
I'm not doing any conversion, and the code I use is:
self.cur.execute("INSERT INTO my_table VALUES(NULL, %s)", (dataDict["hex_value"],)
where dataDict["hex_value"] is 0xC558.
Trying to use int(dataDict["hex_value"])
also gives an error: Invalid literal for int() with base 10: 0xC558
.
Trying to use int(dataDict["hex_value"],base=16)
also gives an error: int() can't convert non-string with explicit base
.
EDIT: the value is of type 'str', as print type(dataDict["hex_value"])
shows (type 'str')
Upvotes: 1
Views: 579
Reputation: 782785
Use:
int(dataDict["hex_value"][2:], base=16)
The substring [2:]
extracts the part of the string after the 0x
prefix. More completely:
self.cur.execute("INSERT INTO my_table VALUES(NULL, %s)", (int(dataDict["hex_value"][2:], base=16), ))
Upvotes: 0
Reputation: 37203
Note that you AREN'T trying to insert a string or an integer.
You say "dataDict["hex_value"] is 0xC558" but you don't say whether it's a string or (as the absence of quotation marks would imply) an integer. It can't be an integer because of the first error you replt. It's clearly not a string due to the second error.
So the issue lies with the type of whatever you have stored in dataDict
, and you don't shoe the code for that. Yet ...
Upvotes: 1