用Java实现向Cassandra数据库中插入和查询数据
所用jar包:
其中jxl.jar和dom4j.jar,jaxen-1.1-beta-6.jar是解析XML文件用的jar包,如果不解析XML文件可以不用。
代码如下:
package com.locationdataprocess;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session; public class QueryAndUpdateData { private Cluster cluster; private Session session; public Cluster getCluster() {
return cluster;
} public void setCluster(Cluster cluster) {
this.cluster = cluster;
} public Session getSession() {
return session;
} public void setSession(Session session) {
this.session = session;
} /**
* 连接节点
*
* @param node
*/
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Connected to cluster: %s\n",
metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
System.out.printf("Datatacenter: %s; Host: %s; Rack: %s\n",
host.getDatacenter(), host.getAddress(), host.getRack());
} this.session = cluster.connect();
} public void insertData(String name) {
String fileName[]={"Zhengye_DriveTesting_08-18.09-07.txt","Zhengye_DriveTesting_08-18.09-13.txt",
"Zhengye_DriveTesting_08-18.17-40.txt","Zhengye_DriveTesting_08-18.17-48.txt",
"Zhengye_DriveTesting_08-19.17-19.txt","Zhengye_DriveTesting_08-20.09-33.txt",
"Zhengye_DriveTesting_08-20.18-05.txt","Zhengye_DriveTesting_08-19.09-08.txt",
"Zhengye_DriveTesting_08-21.18-07.txt","Zhengye_DriveTesting_08-21.09-34.txt"
};
int n = fileName.length;
String sqlGPS = "CREATE TABLE IF NOT EXISTS gpsdata.gps ("
+ "time varchar,"
+ "gps_time varchar,longitude varchar,"
+ "latitude varchar,altitude varchar,"
+ "heading varchar,speed varchar,"
+ "source varchar,satellites varchar,"
+ "PRIMARY KEY (time))";
String sqlTA = "CREATE TABLE IF NOT EXISTS gpsdata.ta ("
+"time varchar,"
+ "version varchar,"
+ "nRecords varchar,"
+ "nSubFrame varchar,"
+ "nSystemFrame varchar,"
+ "DLFrameTimingOffset varchar,"
+ "ULFrameTimingOffset varchar,"
+ "ULTimingAdvance varchar,"
+ "PRIMARY KEY (time))";
String sqlDB = "CREATE TABLE IF NOT EXISTS gpsdata.db ("
+"time varchar,"
+ "version varchar,"
+ "EARFCN varchar,"
+ "CellId varchar,"
+ "nSubFrame varchar,"
+ "RSRP varchar,"
+ "RSRQ varchar,"
+ "NeighborCells varchar,"
+ "DetectedCells varchar,"
+ "NeighborCellId varchar,"
+ "NeighborRSRP varchar,"
+ "NeighborRSRQ varchar,"
+ "PRIMARY KEY (time))";
String insertGPS = "insert into gpsdata.gps("
+ "time,gps_time,longitude,latitude,"
+ "altitude,heading,speed,"
+ "source,satellites)"
+ " values(?,?,?,?,?,?,?,?,?)";
String insertTA = "insert into gpsdata.ta("
+"time,version,nRecords,nSubFrame,nSystemFrame,DLFrameTimingOffset,"
+ "ULFrameTimingOffset,ULTimingAdvance)"
+ " values(?,?,?,?,?,?,?,?)";
String insertDB = "insert into gpsdata.db("
+"time,version,EARFCN,"
+ "CellId,nSubFrame,RSRP,"
+ "RSRQ,NeighborCells,DetectedCells,"
+ "NeighborCellId,NeighborRSRP,NeighborRSRQ)"
+ " values(?,?,?,?,?,?,?,?,?,?,?,?)";
String sql = null, insert=null;
if(name=="GPS"){
sql = sqlGPS;
insert = insertGPS;
}else if(name=="TA"){
sql = sqlTA;
insert = insertTA;
}else if(name=="DB"){
sql = sqlDB;
insert = insertDB;
}
getSession().execute(sql); PreparedStatement psta = getSession().prepare(insert);
BoundStatement boundSta = new BoundStatement(psta);
for(int k=0;k<n;k++){
File file = new File("H:\\项目数据\\Zhengye_Drive_Testing_Data\\"
+ fileName[k]);
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line = null;
if (name == "GPS") {
while ((line = br.readLine()) != null) {
String s = line.trim();
if (s.contains("3D GPS Info")) {
String data[] = new String[9];
data[0] = s.substring(0, 25);
int i = 0;
while (i < 1 && (line = br.readLine()) != null) {
if (!line.equals("")) {
data[1] = line.split("=")[1].trim();
// System.out.println(line.trim());
i++;
}
}
// System.out.println(s);
i = 0;
while (i < 7 && (line = br.readLine()) != null) {
if (!line.equals("")) {
data[i + 2] = line.split("=")[1].trim();
// System.out.println(line.trim());
i++;
}
}
getSession().execute(
boundSta.bind(data[0], data[1], data[2],
data[3], data[4], data[5], data[6],
data[7], data[8]));
}
}
} else if (name == "TA") {
while ((line = br.readLine()) != null) {
String s = line.trim();
if (s.contains("LTE LL1 Serving Cell Frame Timing")) {
String data[] = new String[8];
data[0] = s.substring(0, 25);
// System.out.println(s);
int i = 0;
while (i < 7 && (line = br.readLine()) != null) {
if (!line.equals("")) {
data[i + 1] = line.split("=")[1].trim();
// System.out.println(line.trim());
i++;
}
}
getSession().execute(
boundSta.bind(data[0], data[1], data[2],
data[3], data[4], data[5], data[6],
data[7]));
}
}
} else if(name=="DB"){
while ((line = br.readLine()) != null) {
String s = line.trim();
if (s.contains("LTE ML1 Connected Mode LTE Intra-Freq Meas Results")) {
String data[] = new String[12];
data[9] = "";
data[10] = "";
data[11] = "";
data[0] = s.substring(0, 25);
// System.out.println(s);
int i = 0;
while (i < 8 && (line = br.readLine()) != null) {
if (!line.equals("")) {
data[i + 1] = line.split("=")[1].trim();
// System.out.println(line.trim());
i++;
}
}
int i1 = 0;
while (i1 < 6 && (line = br.readLine()) != null) {
i1++;
}
;
while ((line = br.readLine()) != null
&& line.contains("|")) {
// System.out.println(line);
data[i + 1] += line.split("\\|")[2].trim()
+ " ";
data[i + 2] += line.split("\\|")[3].trim()
+ " ";
data[i + 3] += line.split("\\|")[4].trim()
+ " ";
}
// System.out.println(data[9]);
getSession().execute(
boundSta.bind(data[0], data[1], data[2],
data[3], data[4], data[5], data[6],
data[7], data[8], data[9],
data[10], data[11]));
}
}
} System.out.println(fileName[k]+"插入成功!");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } //查询TA数据
public void loadTAData() {
String select = "select* from gpsdata.ta";
ResultSet resultSet = getSession().execute(select);
int count=0;
for (Row row : resultSet) {
System.out.println("time: "+row.getString("time"));
System.out.println("version: "+row.getString("version"));
System.out.println("nRecords: "+row.getString("nrecords"));
System.out.println("nSubFrame: "+row.getString("nsubframe"));
System.out.println("nSystemFrame: "+row.getString("nsystemframe"));
System.out.println("DLFrameTimingOffset: "+row.getString("dlframetimingoffset"));
System.out.println("ULFrameTimingOffset: "+row.getString("ulframetimingoffset"));
System.out.println("ULTimingAdvance: "+row.getString("ultimingadvance"));
System.out.println("=========================================================");
count++;
}
System.out.println("行数:"+count);
} //查询DB数据
public void loadDBData() {
String select = "select* from gpsdata.db";
ResultSet resultSet = getSession().execute(select);
int count=0;
for (Row row : resultSet) {
System.out.println("time: "+row.getString("time"));
System.out.println("version: "+row.getString("version"));
System.out.println("EARFCN: "+row.getString("earfcn"));
System.out.println("CellId: "+row.getString("cellid"));
System.out.println("nSubFrame: "+row.getString("nsubframe"));
System.out.println("RSRP: "+row.getString("rsrp"));
System.out.println("RSRQ: "+row.getString("rsrq"));
System.out.println("NeighborCells: "+row.getString("neighborcells"));
System.out.println("DetectedCells: "+row.getString("detectedcells"));
System.out.println("NeighborCellId: "+row.getString("neighborcellid"));
System.out.println("NeighborRSRP: "+row.getString("neighborrsrp"));
System.out.println("NeighborRSRQ: "+row.getString("neighborrsrq"));
System.out.println("=========================================================");
count++;
}
System.out.println("行数:"+count);
} //查询GPS数据
public void loadGPSData() {
String select = "select* from gpsdata.gps";
ResultSet resultSet = getSession().execute(select);
int count=0;
for (Row row : resultSet) {
System.out.println("time: "+row.getString("time"));
System.out.println("gps_time: "+row.getString("gps_time"));
System.out.println("longitude: "+row.getString("longitude"));
System.out.println("latitude: "+row.getString("latitude"));
System.out.println("altitude: "+row.getString("altitude"));
System.out.println("heading: "+row.getString("heading"));
System.out.println("speed: "+row.getString("speed"));
System.out.println("source: "+row.getString("source"));
System.out.println("satellites: "+row.getString("satellites"));
System.out.println("=========================================================");
count++;
}
System.out.println("行数:"+count);
} public void close() {
cluster.close();
System.out.println("程序正常关闭!");
} public static void main(String[] args) {
QueryAndUpdateData client = new QueryAndUpdateData();
client.connect("127.0.0.1");
// client.insertData("DB");
// client.loadTAData();
client.loadDBData();
// client.loadGPSData();
client.session.close();
client.close();
}
}
参考链接:
Cassandra 2.x中文教程(22):使用Java驱动操作Cassandra
用Java实现向Cassandra数据库中插入和查询数据的更多相关文章
- Java程序向MySql数据库中插入的中文数据变成了问号
找到mysql的安装目录,修改my.ini文件 (1)如何找到my.ini文件 如果my.ini文件不在MySQL的安装目录下,可能放在隐藏目录,要先去找到ProgramData,(这里要先打开显示隐 ...
- Hibernate框架的基本搭建(一个小的java project的测试向数据库中插入和查询数据的功能)
Hibernate介绍:Hibernate是一种“对象-关系型数据映射组件”,它使用映射文件将对象(object)与关系型数据(Relational)相关联,在Hibernate中映射文件通常以&qu ...
- nodejs 在MYSQL 数据库中插入和查询数据
插入前的数据库: 插入后的数据库: 输出结果: demo var mysql = require('mysql'); var connection = mysql.createConnection({ ...
- MySQL_(Java)使用JDBC向数据库中插入(insert)数据
MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...
- 使用JDBC向数据库中插入一条数据
原谅我是初学者,这个方法写的很烂,以后不会改进,谢谢 /** * 通过JDBC向数据库中插入一条数据 1.Statement 用于执行SQL语句的对象 1.1 通过Connection 的 * cre ...
- Oracle数据库中插入日期型数据(to_date的用法)(转载)
往Oracle数据库中插入日期型数据(to_date的用法) INSERT INTO FLOOR VALUES ( to_date ( '2007-12-20 18:31:34' , 'YYY ...
- SQL语句往Oracle数据库中插入日期型数据(to_date的用法)
Oracle 在操作数据库上相比于其他的 T-sql 有微小的差别,但是在插入时间类型的数据是必须要注意他的 to_date 方法,具体的情况如下: --SQL语句往Oracle数据库中插入日期型数据 ...
- Node.js向MongoDB中插入并查询数据
首先必须要保持Node.js与MongoDB保持连接 具体教程见:Node.js连接MongoDB数据库步骤 插入数据步骤如下 node项目文件如下:在routes文件夹下新建insert.js文件, ...
- 使用JDBC向数据库中插入一条数据(第一次修改版)
增加了一个Tools类,放了一些常用的工具 package com.JDBC.java; import java.io.IOException; import java.io.InputStream; ...
随机推荐
- WebApi参数传递
c# webapi的参数传递方式:1.查询字符串(query string):2.内容主体(content body) 当然也有cookie或url部分或头部信息(header)等其它传方式,这里仅讨 ...
- Java多线程学习总结--线程概述及创建线程的方式(1)
在Java开发中,多线程是很常用的,用得好的话,可以提高程序的性能. 首先先来看一下线程和进程的区别: 1,一个应用程序就是一个进程,一个进程中有一个或多个线程.一个进程至少要有一个主线程.线程可以看 ...
- (phpmyadmin error)Login without a password is forbidden by configuration (see AllowNoPassword) in ubuntu
1.Go to /etc/phpmyadmin/config.inc.php and open it your favorite editor. 2.Search for below line of ...
- 轻松学习Linux之认识内存管理机制
本文出自 "李晨光原创技术博客" 博客,谢绝转载!
- nova 配置文件
控制节点 /etc/nova/nova.conf [DEFAULT]cpu_allocation_ratio=32.0service_down_time = 7200#use_local = True ...
- ArcObjects10.0引用控件报错
错误如下:ArcGIS version not specified. You must call RuntimeManager.Bind before creating any ArcGIS comp ...
- C++11散列表
[C++11散列表] 散列表对应于C++03中的hash_xxx,分为set和map两种 上述的类型将满足对一个容器类型的要求,同时也提供访问其中元素的成员函数: insert, erase, beg ...
- WEB数据挖掘(十三)——关联规则与序列模式(1)
一.Apriori算法简介: Apriori算法是一种挖掘关联规则的频繁项集算法,其核心思想是通过候选集生成和情节的向下封闭检测两个阶段来挖掘频繁项集. Apriori(先验的,推测的)算法应用广泛 ...
- HDU 2437 Jerboas (剪枝搜索)
题意:给定一幅图,图上有两种点T,P.......一只跳鼠在一个T点作为起始点,它想通过图上的路到达某个P点,P点满足如下要求: (1).到达P点的途中路径权值为k的倍数 (2).尽量让路径权值取最小 ...
- 解决UITableView头部空白
解决方式1: self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.ta ...