Python:MySQL错误

2024-09-27 22:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

import MySQLdb    
import random

db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test")

cursor = db.cursor()

var = .3

sql = "INSERT INTO RandomInt 
         (RAND) 
       VALUES 
         (var)" # RandomInt is the name of the table and Rand is the Column Name

cursor.execute(sql)

db.commit()
db.close()

我得到一个错误消息,说Operational Error: (1054, "Unknown column 'var' in 'field list'")为什么我会得到这个错误,以及如何修复这个错误,尽管我已经定义了var?在


Tags: thetestimportlocalhosthostdbsqlis
3条回答

这将解决一个问题:

sql = "INSERT INTO RandomInt (RAND) VALUES (%s)" 
cursors.execute(sql, (var,))

剩下的是写入的表的名称,0.3不是int

编辑:mysqldb的paramstyle是%s不是?。在

var = .3
sql = "INSERT INTO RandomInt (RAND) VALUES (%s)" 
cursor.execute(sql, (var,))

如前所述,var将作为字符串发送到MySQL。
试试看吧:

sql = "INSERT INTO RandomInt (RAND) VALUES (%s)"
cursor.execute(sql, (var,))

编辑:

^{pr2}$

MySQLdb的paramstyle是format;根据DB-API%s

            'format'        ANSI C printf format codes, 
                            e.g. '...WHERE name=%s'

相关问题 更多 >

    热门问题