簡體   English   中英

使用Python在MySQL表中插入值

[英]Inserting values in MySQL table using Python

我在MySQL中有一個帶有以下模式的Bank表:

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

我試圖將Amount作為輸入並使用Python在表中輸入記錄。 我運行以下代碼:

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

但是,它顯示以下錯誤:

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()返回一個字符串:

如果存在prompt參數,則將其寫入標准輸出而不帶尾隨換行符。 然后,該函數從輸入中讀取一行,將其轉換為字符串(剝離尾部換行符),然后返回該行。

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

您需要將其強制轉換為int (根據Amount列類型):

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

cursor = db.cursor()

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

db.commit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM