python to mysql try exception中的未知列

2024-04-26 10:42:12 发布

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

我只想使用python3.2和mysql.connector接口.. 你知道吗

import mysql.connector
filename = "t1.15231.0337.mod35.hdf"
try:
cnx = mysql.connector.connect(user='root', password='', database='etl')
cursor = cnx.cursor()
cursor.execute('SELECT * FROM hdf_file WHERE NAMA_FILE = %s',filename)
rows = cursor.fetchall ()
if rows == []:
    insert_hdf = cursor.execute('INSERT INTO hdf_file VALUES(%s,null,NOW(),null,null,NOW())',filename)
    cursor.execute(insert_hdf)
    cnx.commit()
    cursor.close()
    cnx.close()

除外mysql.connector.Error错误作为错误: print(“出错:{}.format(err))

但上面说:where子句中的未知列'filename' 我试过这样写:

cursor.execute('SELECT * FROM hdf_file WHERE NAMA_FILE = filename')

但我也犯了同样的错误。。。你知道吗


Tags: fromexecuteconnector错误mysqlfilenamewhereselect
1条回答
网友
1楼 · 发布于 2024-04-26 10:42:12

在参数化查询中使用^{}时,查询参数作为序列(例如列表、元组)传递,如果使用命名参数,则作为字典传递。您的代码只传递字符串filename。你知道吗

您的查询可以这样编写:

cursor.execute('SELECT * FROM hdf_file WHERE NAMA_FILE = %s', (filename,))

这里元组(filename,)被传递给execute()。类似地,对于insert查询:

cursor.execute('INSERT INTO hdf_file VALUES (%s, null, NOW(), null, null, NOW())',
                   (filename,))

execute()将返回None,因此将结果存储在insert_hdf变量中没有任何用处。如果您尝试cursor.execute(insert_hdf),它也没有意义,并且会导致错误。你知道吗

相关问题 更多 >