将Python List插入mySQL数据库中的单个列

时间:2014-01-29 17:56:36

标签: python mysql list

您好我正在尝试将python列表插入到单个列中,但它一直在语法上给出错误。 新的。感谢任何帮助。感谢。

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(name)VALUES [\'AdstraGold Microbrewery&amp; Bistro Bar'','Alkaff Mansion Ristorante'','Parco Caffe \','Fat Cat Bistro \',\'Gravity Bar \','The Wine Company(Evans Road)'','' Serenity Spanish Bar&amp;餐厅(VivoCity)\','The New Harbour Cafe&amp;酒吧,''印度时报','日落湾海滩酒吧','朋友@Jelita',''谈唱公鸡唱歌@汤姆森',''日本餐厅酒吧(UE广场)\ ',''Magma德国葡萄酒小酒馆',“Tam Kah Shark's Fin”,“Senso Ristorante&amp;酒吧,''Hard Rock Cafe(HPL House)\',\'St。 James Power Station'','The St. James \',''Brotzeit German Bier Bar&amp;餐厅(Vivocity)\']'

1 个答案:

答案 0 :(得分: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语句。这不是必要的,但它更容易。