gpt4 book ai didi

Python MySQLdb - 获取 ValueError

转载 作者:行者123 更新时间:2023-11-28 23:29:28 25 4
gpt4 key购买 nike

尝试使用 MySQLdb 通过 Python 将列表导入 MySQL...代码如下。

我在运行它时得到一个 ValueError -

query = query % tuple([db.literal(item) for item in args])
ValueError: unsupported format character ',' (0x2c) at index 51

代码_

import MySQLdb
import ystockquote
import re

mydb = MySQLdb.connect(host='localhost',
user= '****',
passwd='****',
db='****')
cur = mydb.cursor()

name = raw_input('please input a symbol_')
data = ystockquote.get_all(name)
stock = data.values()
clean = (", ".join(stock))
#var_string = ', '.join('?' * len(clean))
query_string = 'INSERT IGNORE INTO YAHOO VALUES (\"%s\");' % clean
cur.execute(query_string, clean)
print clean

当我打印 query_string 时,语句看起来不错并且“干净”值看起来状态良好 - 任何帮助将不胜感激。

print clean
1.52, -59.49%, 0.93, 0.17, 800, "1.51 - 1.59", 1.54, 1.59, N/A, -0.01, +5.25%, 0.16, N/A, 0.08, -2.32, N/A, 6.90M, -1.24, N/A, N/A, 1.50, 100, 326754, N/A, N/A, N/A, N/A, 1.51, "NYQ", N/A, "0.93 - 3.90", N/A, "3:48pm - <b>1.58</b>", "Ciber, "+3.95%", N/A, 3700, N/A, N/A, -34.46%, N/A, 2.84, N/A, N/A, N/A, 0.65, N/A, 127.47M, N/A, +69.89%, 2.63, N/A, N/A, 693036, 1.58, -0.65, 73289000, N/A, N/A, -0.83, 0.53, 80680000, N/A, N/A, N/A, Inc. Common Stock", 3.90, "6/14/2016", -0.16, N/A, N/A, 760.00M, +0.06, N/A, N/A, N/A, 2.41, "3:48pm", N/A, "+0.06 - +3.95%", 326754

print query_string
INSERT IGNORE INTO YAHOO VALUES ("1.52, -59.49%, 0.93, 0.17, 800, "1.51 - 1.59", 1.54, 1.59, N/A, -0.01, +5.25%, 0.16, N/A, 0.08, -2.32, N/A, 6.90M, -1.24, N/A, N/A, 1.50, 100, 335969, N/A, N/A, N/A, N/A, 1.51, "NYQ", N/A, "0.93 - 3.90", N/A, "3:51pm - <b>1.58</b>", "Ciber, "+3.95%", N/A, 3700, N/A, N/A, -34.46%, N/A, 2.84, N/A, N/A, N/A, 0.65, N/A, 127.47M, N/A, +69.89%, 2.63, N/A, N/A, 693036, 1.58, -0.65, 73289000, N/A, N/A, -0.83, 0.53, 80680000, N/A, N/A, N/A, Inc. Common Stock", 3.90, "6/14/2016", -0.16, N/A, N/A, 760.00M, +0.06, N/A, N/A, N/A, 2.41, "3:51pm", N/A, "+0.06 - +3.95%", 335969");

最佳答案

.execute以下列方式使用通配符或字符串替换时期望有 2 个参数:

  • query_string with value placeholders %s
  • 将替换上述 %s 的值的元组>

您不需要手动“清理”您的值。我还在查询中包含了列名以使其清楚:

data = ystockquote.get_all(name)
stock = data.values()
columns = data.keys()
columns[columns.index('change')] = '_change'
var_string = '%s' + ',%s' * (len(stock)-1))
query_string = '''
INSERT IGNORE INTO YAHOO
('''+','.join('`%s`' % (c,) for c in columns)+''')
VALUES (%s);''' % var_string
cur.execute(query_string, tuple(stock))

关于Python MySQLdb - 获取 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37820937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com