0

For Python module MySQLdb, I would like to insert or update the database without doing a str() on my data (like int or float or whatever). I have version 1.2.3.

I googled around, looked at many different examples, and checked the API docs and all the examples I found for doing a database insert or update require doing generating a string from your int or float data and then calling the cursor.execute().

For Python module MySQLdb, can you insert or update without calling string format on integers or floats? If yes, how?

( As an aside, I'm not a fan of converting python int/float to str for an insert because it costs CPU and then the receiving mysql server process then has to do the str to int/float conversion which also costs CPU again. Additionally for floats if you do the string representation wrong... your float can lose precision ... or there is rounding sometimes... etc etc. )

0

1 Answer 1

1

If you would use query parameterization, MySQLdb would do the Python-to-database type conversion automatically under-the-hood:

cursor.execute("UPDATE table SET field = %s", (value, ))

Note how the query parameters passed separately in a tuple. And, you don't need to put quotes around placeholders in the query - the driver would also handle it.

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

2 Comments

So the value is not converted to a string inside of the call to cursor.execute()?
@TrevorBoydSmith it can be converted not only to a string, but to an appropriate type depending on a Python type of a parameter - mysqldb will figure it out automagically under-the-hood.

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.