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
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
1 Answer 1
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()
answered Mar 9, 2015 at 1:13
alecxe
476k127 gold badges1.1k silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
noopurballal
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 alecxe
@noopurballal are you sure you're executing the same code as in the answer? Recheck it please.
default