5

I'm attempting to insert some values into a MySQL table, the first 2 values being string and the last being a boolean value. My problem is that I no matter what I do I can't seem to make python/MySQL recognize the boolean as such and insert it. From what I can tell Python is correctly making the last value a boolean, but MySQL isn't seeing it as such. Each time it just defaults to 0 in the table. Below is some pseudo code that is pretty much what I'm trying to do.

conn = MySQLdb.connect(...)
c = conn.cursor()
c.execute("INSERT INTO table (name, string, bool) VALUES (%s,%s,%s,(aName,aString,boolVal))

3 Answers 3

3

See the MySQL docs. A "Boolean" datatype will just be 0 or 1.

The behavior you're seeing is expected.

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

Comments

3

For Python 2.7 and MySQLdb package it works for me in this way.

  1. For columns of varchar type use '%s'
  2. For or boolean, number use just %s, %d, %i.
INSERT INTO table (string, bool) VALUES ('%s',%s) % ('string',True)`

Comments

2

if the value is True or False in python you can use int()

>>> a = True
>>> int(a)
1
>>>

conn = MySQLdb.connect(...)
c = conn.cursor()
c.execute("INSERT INTO table (bool) VALUES (%s)",( int(boolVal),))

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.