1

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')

7
  • 2
    what type is dataDict['hex_value']? Commented Mar 6, 2014 at 23:30
  • what happens if you just print(dataDict['hex_value']) Commented Mar 6, 2014 at 23:37
  • Thanks. What does repr(dataDict['hex_value']) give you? Commented Mar 6, 2014 at 23:51
  • If it is str I wonder why on earth you get the exception when you do: int(dataDict["hex_value"],base=16) Commented Mar 6, 2014 at 23:54
  • MySQL hex literals use the syntax X'C558', not 0xC558. So it's treating that value as a string, not a hex number. I suggest you convert it to an integer in Python before doing the INSERT. Commented Mar 7, 2014 at 0:01

2 Answers 2

1

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 ...

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

2 Comments

Probably. I was going to edit it, but with an acceptable answer in place maybe I should just delete it?
I don't think anyone really sees it as that helpful, and despite the upvote I would be happy to let it go (since the real answer was nothing to do with the data types).
0

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), ))

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.