[英]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');
這可能也有幫助。
編輯
我也使流程自動化:
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.