gpt4 book ai didi

java - 使用java从cassandra读取数据

转载 作者:行者123 更新时间:2023-11-30 02:20:24 24 4
gpt4 key购买 nike

 My sample  cassandra table looks like        

id | article_read | last_hours | name
----+-----------------------------------
5 | [4, 5, 6] | 5 | shashank
10 | [12, 88, 32] | 1 | sam
8 | [4, 5, 6] | 8 | aman
7 | [5, 6] | 7 | ashif
6 | [4, 5, 6] | 6 | amit
9 | [4, 5, 6] | 9 | shekhar

我的java代码使用cql查询从Cassandra表读取数据,

     Scanner sc = new Scanner(System.in);
System.out.println("enter name1 ");
String name1 = sc.nextLine();
System.out.println("enter name2");
String name2 = sc.nextLine();

Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect("tp");

PreparedStatement queryStmt = session.prepare("select article_read from bat where name = ?");
ResultSet result1 = session.execute(queryStmt.bind(name1));

ResultSet result2 = session.execute(queryStmt.bind(name2));
System.out.println(result1.all());
System.out.println(result2.all());

if(result1.equals(result2))
{
System.out.println("100% sentiment ");
}
else
{
System.out.println("no sentiment ");
}
}

看看我的代码,它正在运行,但是当我输入 name1、name2 shashank 和 aman 时,它给出 100%,但是当给出 shashank 和 ashif 时,结果再次 100% 匹配..

最佳答案

使用PreparedStatement

首先只准备一次查询,如下所示:

//Prepared only once. 
PreparedStatement queryStmt = session.prepare("select * from bat where name = ?");

然后您可以多次使用它,如下所示:

ResultSet result1 = session.execute(queryStmt.bind("shashank"));
ResultSet result2 = session.execute(queryStmt.bind("aman"));
<小时/>

已编辑

try (Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Session session = cluster.connect("test")) {
Scanner sc = new Scanner(System.in);
System.out.println("enter name1 ");
String name1 = sc.nextLine();
System.out.println("enter name2");
String name2 = sc.nextLine();

PreparedStatement queryStmt = session.prepare("select article_read from bat where name = ?");
ResultSet result1 = session.execute(queryStmt.bind(name1));
ResultSet result2 = session.execute(queryStmt.bind(name2));


if (result1.one().getList("article_read", Integer.class).equals(result2.one().getList("article_read", Integer.class))) {
System.out.println("100% sentiment ");
} else {
System.out.println("no sentiment ");
}
}

关于java - 使用java从cassandra读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47030798/

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