You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作Cassandra更新列报错:无法拼接str与UUID对象求助

Fixing "TypeError: cannot concatenate 'str' and 'UUID' objects" in Cassandra Python Script

Hey there, let's break down and fix this error you're hitting.

What's causing the error?

The issue here is that row.id is a UUID object (not a plain string), and you're trying to concatenate it directly with your SQL query string. Python doesn't allow mixing string and UUID types in concatenation, hence the TypeError you're seeing.

You could explicitly convert the UUID to a string using str(row.id) to make the concatenation work. But a big caveat—this approach carries SQL injection risks if your data isn't fully trusted, so it's not ideal for production code:

active = session.execute("select id, status from address where status = 'A'")
for row in active:
    session.execute("update address set status = 'ACTIVE' where id = '" + str(row.id) + "'")

Solution 2: Use parameterized queries (best practice)

The right, secure way to handle this is to use parameterized queries, which the Cassandra Python driver supports natively. This method automatically handles type conversion (including UUIDs) and eliminates SQL injection risks entirely. Here's how to rewrite your code:

active = session.execute("select id, status from address where status = 'A'")
update_query = "update address set status = 'ACTIVE' where id = %s"
for row in active:
    session.execute(update_query, (row.id,))

Why this works

  • The %s acts as a safe placeholder for the UUID value.
  • When you pass (row.id,) as the second argument to session.execute(), the driver takes care of converting the UUID object to the exact format Cassandra expects.
  • This is the industry-standard, maintainable way to interact with Cassandra (and most databases) from Python.

内容的提问来源于stack exchange,提问作者Hari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:29:28