3

I have a Bank table in MySQL with the following schema:

`User_id` int(11) NOT NULL AUTO_INCREMENT,
`Amount` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`User_id`)

I am trying to take Amount as input and enter a record in the table using Python. I run the following code for the same:

print " enter the bank amount"
Amount = raw_input()
cursor.execute('''INSERT into Bank (Amount)
                  values (%d)''',
                  (Amount))
cursor.execute('commit')

But, it shows following error:

Traceback (most recent call last):
  File "create_user.py", line 23, in <module>
    (Amount))
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
    query = query % tuple([db.literal(item) for item in args])
TypeError: %d format: a number is required, not str

1 Answer 1

2

raw_input() returns a string:

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

>>> test = raw_input()
1
>>> test
'1'
>>> type(test)
<type 'str'>

You need to cast it to int (according to the Amount column type):

amount = int(raw_input())  # TODO: handle exceptions?

cursor = db.cursor()

cursor.execute("""
    INSERT INTO 
        Bank (Amount)
    VALUES 
        (%d)
""", (amount, ))

db.commit()
Sign up to request clarification or add additional context in comments.

2 Comments

Byconverting string to int , it shows the following error Traceback (most recent call last): File "create_user.py", line 23, in <module> (Amount )) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute query = query % tuple([db.literal(item) for item in args]) TypeError: 'int' object is not iterable
@noopurballal are you sure you're executing the same code as in the answer? Recheck it please.

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.