Apache Cassandra 中的无效字符串常量错误(使用 Python)

hrm*_*llo 4 python cassandra python-3.x

我是 Apache Cassandra(使用 Python 3)的新手,我正在尝试基于 csv 文件创建一个表。文件如下所示:https : //i.stack.imgur.com/aYRS1.jpg(抱歉,我没有足够的声望点来张贴图片)

首先我创建表

query1 = "CREATE TABLE IF NOT EXISTS table1(artist text, title text, \
            length text, sessionId text, itemInSession text, PRIMARY KEY (sessionId, title, artist))"     

session.execute(query1)
Run Code Online (Sandbox Code Playgroud)

然后我尝试读取文件并将所需的数据插入表中:

file = 'event_datafile_new.csv'

with open(file, encoding = 'utf8') as f:
    csvreader = csv.reader(f)
    next(csvreader) # skip header
    for line in csvreader:
        query = "INSERT INTO table1(artist, title, length, sessionId, itemInSession)"
        query = query + "VALUES(%s, %s, %s, %s, %s)"
        session.execute(query, (line[0], line[9], line[5], line[8], line[3]))
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

---> 13         session.execute(query, (line[0], line[9], line[5], line[8], line[3]))

/opt/conda/lib/python3.6/site-packages/cassandra/cluster.cpython-36m-x86_64-linux-gnu.so in cassandra.cluster.Session.execute (cassandra/cluster.c:38536)()

/opt/conda/lib/python3.6/site-packages/cassandra/cluster.cpython-36m-x86_64-linux-gnu.so in cassandra.cluster.ResponseFuture.result (cassandra/cluster.c:80834)()

InvalidRequest: Error from server: code=2200 [Invalid query] message="Invalid STRING constant (288.9922) for "length" of type float"
Run Code Online (Sandbox Code Playgroud)

即使我尝试在 INSERT 语句中将“长度”的格式更改为浮动 - 并将 %s 更改为 %f - 它也没有锻炼。有谁知道可能是什么问题?非常感谢!:)

小智 11

每当您使用 csvreader 从文件中读取时:“从 csv 文件中读取的每一行都作为字符串列表返回除非指定了 QUOTE_NONNUMERIC 格式选项,否则不会执行自动数据类型转换”来自:https ://docs.python.org /3/library/csv.html

使用以下类型定义的表:

"CREATE TABLE IF NOT EXISTS table1(artist text, title text, \
            length double, sessionId int, itemInSession int, PRIMARY KEY (sessionId, title, artist))"
Run Code Online (Sandbox Code Playgroud)

如果您将值转换为正确的类型,它应该可以工作。我试过了,它奏效了。

session.execute(query, (line[0], line[9], float(line[5]), int(line[8]), int(line[3])))
Run Code Online (Sandbox Code Playgroud)