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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With