我在Python pymysql写入数据库时出现下面错误:
C:\Python27\python.exe E:/pythonbao/bao1/.idea/20160718.py
Traceback (most recent call last):
File "E:/pythonbao/bao1/.idea/20160718.py", line 35, in <module>
"%s, %s, %s, %s, %s, %s, %s)", value)
File "C:\Python27\lib\site-packages\pymysql\cursors.py", line 159, in execute
query = self.mogrify(query, args)
File "C:\Python27\lib\site-packages\pymysql\cursors.py", line 138, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not enough arguments for format string
百度后把“%s”改为“%%s”没用。
下面是代码
# -*- coding: utf-8 -*-
import urllib2
import pymysql
import time
from bs4 import BeautifulSoup
today = time.strftime('%%Y-%%m-%%d',time.localtime(time.time()))
loginHeaders = {
'Host':'www.czce.com.cn',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36',
'Referer':'http://www.czce.com.cn/portal/jysj/mrhq/A091101index_1.htm',
'Content-Type':'text/html',
'Connection':'keep-alive'
}
url='http://www.czce.com.cn/portal/DFSStaticFiles/Future/2016/20160804/FutureDataDailyOI.htm'
request = urllib2.Request(url, headers=loginHeaders)
opener = urllib2.build_opener()
response = opener.open(request)
content = response.read().decode('gbk').replace("</tr>","").replace("<tr>","")
soup = BeautifulSoup(content,'lxml').findAll(id="senfe")[0]
table = soup.text.split("\n")
conn = pymysql.connect(host="192.168.1.98",user="root",passwd="root",db="test",charset='utf8')
cur = conn.cursor()
value = []
for i in range(0,8):
value.append((today,table[16+14*i],table[17+14*i],table[18+14*i],table[19+14*i],
table[20+14*i],table[21+14*i],table[22+14*i],table[23+14*i],
table[24+14*i],table[25+14*i],table[26+14*i],table[27+14*i],table[28+14*i],table[29+14*i]))
cur.execute("INSERT INTO zhujiagewang"
"(collecttime,pinzhongyuefen,zuojiesuan,jinkaipan,zuigaojia,zuidijai,"
"jinshoupan,jinjiesuan,zhangdie1,zhangdie2,chengjiaoliang,kongpanliang,"
"zengjianliang,chengjiaoe,jiaogejiesuanjia) "
"VALUES(%s,%s, %s, %s, %s, %s, %s, %s,"
"%s, %s, %s, %s, %s, %s, %s)", value)
conn.commit()
cur.close()
conn.close()
数据库数据:
Judging from the exception information, it is because there is a problem with string formatting.
Actually, what you want to do is to execute the following insert statement for each element in the value list:
Or consider batch inserting data like below:
There is a corresponding executemany method.
Try assigning values one by one like this
value
改成value[i]