2014-01-29 32 views
0

嗨,我试图插入一个Python列表到一个列中,但它一直给出一个语法错误。 对此不了解。感谢任何帮助。谢谢。将Python列表插入到mySQL数据库中的单个列中

from time import time 
import MySQLdb 
import urllib 
import re 
from bs4 import BeautifulSoup 

db = MySQLdb.connect("localhost","testuser","test123","testdb") 
cursor = db.cursor() 

x=1 
while x<2: 

    url = "http://search.insing.com/ts/food-drink/bars-pubs/bars-pubs?page=" +str(x) 
    htmlfile = urllib.urlopen(url) 
    soup = BeautifulSoup(htmlfile) 
    reshtml = [h3.a for h3 in soup.find("div", "results").find_all("h3")] 
    reslist = [] 
    for item in reshtml: 

      res = item.text.encode('ascii', 'ignore') 
      reslist.append(' '.join(res.split())) 


    sql = "INSERT INTO insing(name) \ 
    VALUES %r" \ 
    % reslist 




    try: 
     cursor.execute(sql) 
     db.commit() 
    except: 
     db.rollback() 
     db.close() 

     x += 1 

对SQL的输出是

'INSERT INTO insing(名称)值[\' AdstraGold酿酒&小酒吧\ '\ 'Alkaff大厦意大利餐厅\' \' Parco公司来自Caffe \ ','肥猫小酒馆','重力酒吧','葡萄酒公司(埃文斯路)','宁静西班牙酒吧&餐厅(怡丰城)','新港咖啡厅&酒吧“,”印度时报“,”日落湾海滩酒吧“,”朋友@ Jelita“,”谈话唱歌汤姆森“,”En Japanese Bar(UE Square) ','岩浆德国酒小酒馆','谭嘉鲨的鱼翅','Senso Ris torante & Bar','Hard Rock Cafe(HPL House)','St。詹姆斯电站\ '\ '圣詹姆斯\',\ 'Brotzeit德国比尔酒吧&餐厅(怡丰城)\']'

+0

将列表放入一个字符串并将其保存到数据库中。如果你需要列表形式,当你加载它时,数据库会将它拆分回列表中。 – IanAuld

回答

0

怎么样

insert into table(name) values ('name1'), ('name2'), ... , ('name36'); 

Inserting multiple rows in a single SQL query?

这可能也有帮助。

编辑

我自动化的过程,以及:

dataSQL = "INSERT INTO PropertyRow (SWID, Address, APN, PropertyType, PermissableUse, UseDetail, ReviewResult, Analysis, DocReviewed, AqDate, ValuePurchase, ValueCurrent, ValueDate, ValueBasis, ValueSale, SaleDate, PropPurpose, LotSize, Zoning, ParcelValue, EstRevenue, ReqRevenue, EnvHistory, TransitPotential, PlanObjective, PrevHistory, LastUpdDate, LastUpdUser)" 
fields = "VALUES ("+"'"+str(rawID)+"', " 

if(cell.ctype != 0): 
    while column < 27: 
    #column 16 will always be blank 
    if (column == 16): 
     column += 1 
    #column 26 is the end 
    if (column == 26): 
     fields += "'"+str(sh.cell_value(rowx=currentRow, colx=column)) + "'" 
    else: 
     #append to the value string 
     fields += "'"+str(sh.cell_value(rowx=currentRow, colx=column)) + "', " 
     #print fields 
     column+=1 
     fields += ');' 
     writeFyle.write(dataSQL) 
     writeFyle.write(fields) 

在此实现我写的,我想插入每一行的INSERT语句。这不是必要的,但它更容易。

+0

我正在自动执行此过程,因此这是过于人工操作 – Gerayap

相关问题