【问题标题】:Python MySQLdb Insert TypeError: not all arguments converted during string formattingPython MySQLdb Insert TypeError:字符串格式化期间并非所有参数都转换
【发布时间】:2014-03-06 11:02:43
【问题描述】:

我正在尝试将一些值插入到我的数据库中

urls =("http://www.**********.net/?page=match")
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(urls,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)

tournament = soup.find('div',{'class':['content-body']})
match_times = tournament.find_all("div", style = "width:10%; float:left;")
match_names = tournament.find_all("div", style = "width:46%; float:left; margin-left:2%; margin-right:2%")
tournys = tournament.find_all("div", style = "width:40%; float:left; overflow:hidden;")


for element in zip(match_times, match_names, tournys):
    results = element[0].text, element[1].text, element[2].text
    matchday=datetime.strptime(results[0], "%d/%m/%y").strftime("%d-%m-%Y")
    info= results[1],results[2],matchday
    conn= MySQLdb.connect(host='localhost',user='root',passwd='',db='sport')
    c = conn.cursor()
    query = "INSERT INTO todaysmatches (match, tournament, matchdate) VALUES (%s,%s,%s)"
    c.executemany(query, info)
    conn.commit()
    conn.close()
    print  info
    print '==================='

match 是 varchar(150) ,比赛 varchar(150) 和 matchdate 是 DATE

这是打印信息的示例:

(u'\n\xa0bestest \n9 - 16\ntryPANTS\xa0\n\n', u'\xa0Razer CS:GO Tournament', '08-12-2013')

【问题讨论】:

  • 尝试info= results[1].strip(), results[2].strip(), matchday 并尝试@avoid3d 提到的内容
  • 将错误更改为 VALUES \n('Rasta.eon\\n2 - 1\\nRasta.Xd','Razer CS:GO' at line 1")
  • ProgrammingError: (1064, "您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,了解在 'match,tournamentname,matchdate 附近使用的正确语法) VALUES \n ('Rasta.eon 2 - 1 Rasta.Xd','Razer C' at line 1")
  • 当我打印 info [u' Rasta.eon 2 - 1 Rasta.Xd ', u'Razer CS:GO Tournament 2', u'26-02 时出现同样的错误,这是列表之一-2014']
  • 你可以试试info= str(results[1].strip()), str(results[2].strip()), matchdayc.execute(query, info)。我认为它应该有效。

标签: python mysql-python


【解决方案1】:

换行试试:

# This expects a list as it's second argument, you are giving it a tuple.
c.executemany(query, info)

到这里:

c.executemany(query, [info])

如果可行,那么您可能需要阅读文档,并了解在您只需插入一行时是否有更好的插入数据方法。 (几乎可以肯定。)

【讨论】:

  • 现在我得到了这个错误 ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that applicable to your MySQL server version for the right syntax to use near 'match,锦标赛, matchdate) VALUES \n('\\n\xa0Rasta.eon\\n2 - 1\\nRasta.Xd \xa0','\xa0Ra' at line 1")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
相关资源
最近更新 更多