Apache Cassandra中使用无效的STRING常量错误(使用Python)

时间:2019-03-21 23:50:50

标签: python python-3.x cassandra

我是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)

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

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]))

但是,出现以下错误:

---> 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"

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

1 个答案:

答案 0 :(得分:2)

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

具有定义为以下类型的表:

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

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

session.execute(query, (line[0], line[9], float(line[5]), int(line[8]), int(line[3])))