Python在mysql中插入html

ih99xse1  于 2023-04-19  发布在  Mysql
关注(0)|答案(2)|浏览(147)

如何用Python在mysql中插入html?

sql_data = "INSERT INTO `index_table`.`tab_data` (`id`, `content`, `copyfrom`) VALUES ( NULL, '%s','0')"

我想插入的html代码是这样的

<p><img src='http://img.domain.com/topic/image/20150731/db9475df317519db7622c25f23a42b0130700277.jpg' /></p>

我的python代码

content = "<p><img src='http://img.domain.com/topic/image/20150731/db9475df317519db7622c25f23a42b0130700277.jpg' /></p>" 
tx.execute(sql_data % (tx.commit(str(content))) )

但它不起作用。
下面是更多Python代码

class MysqlPipeline(object):  
def __init__(self):                              
    self.dbpool = adbapi.ConnectionPool('MySQLdb', 
            host = 'localhost', 
            db = 'index',  
            user = 'name',  
            passwd = 'pass',  
            cursorclass = MySQLdb.cursors.DictCursor,  
            charset = 'utf8',  
            use_unicode = False
    )  

# pipeline dafault function                      
def process_item(self, item, spider):  
    query = self.dbpool.runInteraction(self._conditional_insert, item)  
    return item  

# insert the data to databases                    
def _conditional_insert(self, tx, item): 
    now_data = str(time.strftime('%Y%m%d',time.localtime(time.time())))  

    sql_data = ('INSERT INTO `index`.`news_data` (`id`, `content`, `maxcharperpage`, `allow_comment`) VALUES ( LAST_INSERT_ID(), "%s", "10000", "1")')
    try:
        thumbname = item['images'][0]['path']
        title = str(item['title'][0]) 
        picid = item['catid']
        image_locals = "http://img.domain.com/topic/image/"+now_data+"/"+thumbname
        #print maxid
        localimgs = list()
        for img in item['images']:
            imgsrc = img['path']
            #localimg = str("<p><img src='http://img.domain.com/topic/image/"+now_data+"/"+imgsrc+"' /></p>").replace('full/','')
            localimg = imgsrc
            localimgs.append(localimg)
        neirong = ''.join(localimgs)# neirong is a str object, html code.
        print neirong

        tx.execute(sql_data , [neirong]) # Is this line right? but it doesn't work

    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
    return item

可能有更多的信息你可以找到

cpjpxq1n

cpjpxq1n1#

假设tx是一个游标对象,将content作为参数传递,而不是自己构建一个sql。否则,您应该考虑引用自己。(以防止SQL注入)

sql_data = (
    "INSERT INTO `index_table`.`tab_data` (`id`, `content`, `copyfrom`) "
    "VALUES (NULL, %s, '0')")
content = "... html ..."
tx.execute(sql_data, [content])
# connection_object.commit()
mwg9r5ms

mwg9r5ms2#

它需要executemmany()和list,并在插入之前转换为字符串。

sql_data = (
"INSERT INTO `index_table`.`tab_data` (`id`, `content`, `copyfrom`) "
"VALUES (NULL, %s, '0')")
content = "<p>...</p>"
content = str(content)
tx.executemany(sql_data, [content])

相关问题