将Python列表插入mySQL数据库中的一列

2024-10-01 17:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我试图在一列中插入一个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 & 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 Harbour Cafe & Bar\', \'Indian Times\', \'Sunset Bay Beach Bar\', \'Friends @ Jelita\', \'Talk Cock Sing Song @ Thomson\', \'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\', \'The St. James\', \'Brotzeit German Bier Bar & Restaurant (Vivocity)\']'


Tags: thefromimporturldbtimebarurllib
1条回答
网友
1楼 · 发布于 2024-10-01 17:22:02

怎么办

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

Inserting multiple rows in a single SQL query?

这可能也有帮助。在

编辑

我还自动化了流程:

^{pr2}$

在这个实现中,我为要插入的每一行编写一个insert语句。这没必要,但容易得多。在

相关问题 更多 >

    热门问题