gpt4 book ai didi

python - 使用 Python 填充 Cassandra 数据库

转载 作者:搜寻专家 更新时间:2023-10-30 20:35:05 24 4
gpt4 key购买 nike

我在 Linux 平台上使用 Cassandra 数据库。我想使用来自远程服务器的 Python 代码将图像数据插入 Cassandra 数据库。之前,我编写了一个 python 代码,将图像的数据从远程服务器插入到 MySQL 数据库中。请看下面的 MySQL 代码

#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import psycopg2
import sys
import MySQLdb
def read_image(i):
filename="/home/faban/Downloads/Python/Python-Mysql/images/im"
filename=filename+str(i)+".jpg"
print(filename)
fin = open(filename)
img = fin.read()
return img
con = MySQLdb.connect("192.168.50.12","root","faban","experiments" )
with con:
print('connecting to database')
range_from=input('Enter range from:')
range_till=input('Enter range till:')
for i in range(range_from,range_till):
cur = con.cursor()
data = read_image(i)
cur.execute("INSERT INTO images VALUES(%s, %s)", (i,data, ))
cur.close()
con.commit()
con.close()

这段代码成功地将数据插入到位于 .12 的 MySQL 数据库中我想修改相同的代码以将数据插入同样位于 .12 的 Cassandra 数据库请在这方面帮助我。

最佳答案

如果我创建一个像这样的简单表格:

CREATE TABLE stackoverflow.images (
name text PRIMARY KEY,
data blob);

我可以使用与您的类似的 Python 代码加载这些图像,但使用 DataStax Python Cassandra 驱动程序进行一些小的更改(pip install cassandra-driver):

#imports for DataStax Cassandra driver and sys
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import SimpleStatement
import sys

#reading my hostname, username, and password from the command line; defining my Cassandra keyspace as as variable.
hostname=sys.argv[1]
username=sys.argv[2]
password=sys.argv[3]
keyspace="stackoverflow"

#adding my hostname to an array, setting up auth, and connecting to Cassandra
nodes = []
nodes.append(hostname)
auth_provider = PlainTextAuthProvider(username=username, password=password)
ssl_opts = {}
cluster = Cluster(nodes,auth_provider=auth_provider,ssl_options=ssl_opts)
session = cluster.connect(keyspace)

#setting my image name, loading the file, and reading the data
name = "IVoidWarranties.jpg"
fileHandle = open("/home/aploetz/Pictures/" + name)
imgData = fileHandle.read()

#preparing and executing my INSERT statement
strCQL = "INSERT INTO images (name,data) VALUES (?,?)"
pStatement = session.prepare(strCQL)
session.execute(pStatement,[name,imgData])

#closing my connection
session.shutdown()

希望对您有所帮助!

关于python - 使用 Python 填充 Cassandra 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com