我在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()
数据库数据:
으아악
예외 정보로 판단하면 문자열 형식에 문제가 있기 때문입니다.
으아악실제로 원하는 작업은 값 목록의 각 요소에 대해 다음 삽입 문을 실행하는 것입니다.
또는 다음과 같이 데이터를 일괄 삽입하는 것을 고려해 보세요.
으아악해당 Execmany 메소드가 있습니다.
value
을value[i]
으로 변경하고 값을 하나씩 할당해 보세요