Python无法连接'str'和'int'对象

oll*_*lle -1 python xml mysql parsing

我正在尝试将XMLfile解析为mysqldb.这是xml

<categories>
<category id="28">Woman</category>
<category id="277" parentId="28">T-Shirts</category>
<category id="140" parentId="277">shorts</category>
</category>
Run Code Online (Sandbox Code Playgroud)

的.py

for category in categories:
        for item in category.getElementsByTagName("category"):
            category_name = item.childNodes[0].nodeValue.encode("utf-8")
            category_id = int(item.getAttribute('id'))
            category_parentId = item.getAttribute('parentId')
#connect etc
sqlFillCategories = "INSERT INTO categories(category_id, category_parentId, shop_id, category_name) VALUES ('"+category_id + "', '" + category_parentId + "', '" + TREND_BRANDS_SHOPID + "', '" + category_name + "');"
Run Code Online (Sandbox Code Playgroud)

错误:

Traceback (most recent call last):
  File "E:/python1/fanswell/parse.py", line 23, in <module>
    sqlFillCategories = "INSERT INTO categories(category_id, category_parentId, shop_id, category_name) VALUES ('"+category_id + "', '" + category_parentId + "', '" + TREND_BRANDS_SHOPID + "', '" + category_name + "');"

TypeError: cannot concatenate 'str' and 'int' objects
Run Code Online (Sandbox Code Playgroud)

为什么会这样?怎么了?

Lew*_*rin 5

int和str是不同的类型.

要将int连接到str,

你需要做一个intstr转换.也就是说,例如:

"Hello World " + str(1)
Run Code Online (Sandbox Code Playgroud)

所以你可能想要:

 sqlFillCategories = "INSERT INTO categories(category_id, category_parentId,
 shop_id, category_name) VALUES ('"+str(category_id) + "', '" +
 str(category_parentId) + "', '" + str(TREND_BRANDS_SHOPID) + "', '" 
 + category_name + "');"
Run Code Online (Sandbox Code Playgroud)

编辑:你的插入语句在循环之外,试试这个:

sqlFillCategories =''
for category in categories:
        for item in category.getElementsByTagName("category"):
            category_name = item.childNodes[0].nodeValue.encode("utf-8")
            category_id = int(item.getAttribute('id'))
            category_parentId = item.getAttribute('parentId') 
            sqlFillCategories += 
            "INSERT INTO categories(category_id, category_parentId, shop_id, 
            category_name) VALUES ('"+category_id + "', '" + 
            category_parentId + "','" + TREND_BRANDS_SHOPID + "',
             '" + category_name + "');"
Run Code Online (Sandbox Code Playgroud)

什么sqlFillCategories时候会执行一堆插入.