繁体   English   中英

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

[英]Insert Python List into a single column in mySQL Database

嗨,我正在尝试在单列中插入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的输出是

'INSINS INTO insing(name)VALUES [\\'AdstraGold Microbrewery&Bistro Bar \\',\\'Alkaff Mansion Ristorante \\',\\'Parco Caffe \\',\\'The Fat Cat Bistro \\',\\'Gravity Bar \\' \\'The Wine Company(Evans Road)\\','Serenity Spanish Bar&Restaurant(VivoCity)\\',\\'The New Harbor Cafe&Bar \\',\\'Indian Times \\',\\'Sunset Bay Beach Bar \\ ',\\'Jelita的朋友','Thomson的Tock Cock Sing Song','En Japanese Dining Bar(UE Square)','Magma German Wine Bistro',“ Tam Kah Shark's Fin”,\\'Senso Ristorante&Bar \\',\\'Hard Rock Cafe(HPL House)\\',\\'St。 James Power Station \\',\\'St。James \\',\\'Brotzeit German Bier Bar&Restaurant(Vivocity)\\']'

关于什么

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

在单个SQL查询中插入多行?

这可能也有帮助。

编辑

我也使流程自动化:

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)

在此实现中,我为要插入的每一行编写了一条插入语句。 这不是必需的,但要容易得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM