【问题标题】:Inserting values in MySQL table using Python使用 Python 在 MySQL 表中插入值
【发布时间】:2015-05-10 03:02:06
【问题描述】:

我在 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

【问题讨论】:

    标签: python mysql python-2.7


    【解决方案1】:

    raw_input() 返回一个字符串:

    如果提示参数存在,则将其写入标准输出 没有尾随换行符。然后该函数从输入中读取一行, 将其转换为字符串(去除尾随的换行符),并返回 那个。

    >>> 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()
    

    【讨论】:

    • 通过将 string 转换为 int ,它显示以下错误Traceback (most recent call last): File "create_user.py", line 23, in &lt;module&gt; (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 你确定你正在执行与答案中相同的代码吗?请重新检查。
    猜你喜欢
    • 2019-01-08
    • 2019-04-08
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2011-11-01
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多