I am new to Cassandra and i am working on a project that uses Cassandra as DB. The Cassandra is installed in another device and i will have to save it to the db remotely.
I have little knowledge about Cassandra and its functionality but I'm good with MySQL.
What are the steps to save a message into Cassandra?
Can I use the same database that I used with MySQL?
I believe that I will have to connect to the Cassandra Server and then save it.
Cluster cluster = Cluster.builder().addContactPoint("localhost").withPort(3306).build();
I have used this statement to connect to Cassandra. (replacing localhost to the ip of the device)
Your best bet here is to start with the java driver docs. If you use maven its quite easy to setup, but I often find the examples don't always give a full pom.xml so you can use some of the examples in the github project
The quick start guide gives a very simple example:
Cluster cluster = null;
try {
cluster = Cluster.builder()
.addContactPoint("127.0.0.1")
.build();
Session session = cluster.connect();
ResultSet rs = session.execute("select release_version from system.local");
Row row = rs.one();
System.out.println(row.getString("release_version"));
} finally {
if (cluster != null) cluster.close();
}
Some other items of interest are the connection pooling and load balancing
Create a session with the cluster created and the keyspace:
Session session = cluster.connect("keyspace");
create keyspace if u don't have one.
then use
session.execute(query);
to execute any query of your choice.
query has to be string and not null.
eg:
String query= "INSERT INTO keyspace.table_name (id, lastname, firstname) VALUES (6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47, 'KRUIKSWIJK','Steven');";
session.execute(query);
Related
I'm new to AWS Lambda, We have an already developed application which relies on Spring Data JPA for data access layer. Now in progress of separating individual modules as separate microservices. We are moving on to AWS Lambda. I'm able to see many examples which show how to connect to RDBMS using simple JDBC connection.
How to use Spring Data JPA in AWS Lambda for data access layer?.
Its the same way you would on your traditional servers or container instances (essentially thats all AWS Lambda is a short lived container).
System.out.println("Connecting to database...");
String url = "jdbc:mysql://master.zxxsecygfasd.eu-west-1.rds.amazonaws.com:3306/";
String database = "db_name";
String userName = "root";
String password = "somepass";
try (Connection connection = DriverManager.getConnection(url + database, userName, password)) {
} catch (Exception e) {
System.out.println("Database connection: Failed");
e.printStackTrace();
}
There are however some caveats this will be only able to hit a publicly accessible database from lambda. If you put your Lambda in a specific VPC you are going to need to configure roles for it, security groups and access control.
And finally on the note of JPA there are examples floating out there (Its also pretty standard). I have used hibernate before my personal opinion is that it was a bit heavy.
I am using SymmetricDS tool for Syncing data between MySql database for Server and SQLite database for Android.i am done with fetching data from the server and sending data to the server with this tool. but i don't get any event for Syncing is started and Syncing is completed. with that i want to show progress dialog till all server data synced completely to my table.
i am not able to find something related to this in their documents over their website.please help me with this.i am working on this issue from last 4 days but could not able to find solution yet.
I have done this so far:
final String HELPER_KEY = "Key";
Logger.e("TAG", "Key " + HELPER_KEY);
SQLiteOpenHelperRegistry.register(HELPER_KEY, mDatabaseHelper);
Intent intent = new Intent(c, SymmetricService.class);
// Notify the service of the database helper key
intent.putExtra(SymmetricService.INTENTKEY_SQLITEOPENHELPER_REGISTRY_KEY, HELPER_KEY);
intent.putExtra(SymmetricService.INTENTKEY_REGISTRATION_URL, Constants.SYMMETRICDS_URL);
intent.putExtra(SymmetricService.INTENTKEY_EXTERNAL_ID, node);
intent.putExtra(SymmetricService.INTENTKEY_NODE_GROUP_ID, Constants.SYMMETRICDS_GROUP_ID);
intent.putExtra(SymmetricService.INTENTKEY_START_IN_BACKGROUND, true);
Properties properties = new Properties();
// initial load existing notes from the Client to the Server
properties.setProperty(ParameterConstants.ENGINE_NAME, node);
properties.setProperty(ParameterConstants.AUTO_RELOAD_REVERSE_ENABLED, "true");
intent.putExtra(SymmetricService.INTENTKEY_PROPERTIES, properties);
c.startService(intent);
You can run this SQL query:
SELECT sob.status, sob.node_id, COUNT(*) as cnt, 'outgoing' AS direction
FROM SYM_OUTGOING_BATCH sob
GROUP BY sob.status, sob.node_id
UNION ALL
SELECT sob.status, sob.node_id, COUNT(*) as cnt, 'incoming' AS direction
FROM SYM_INCOMING_BATCH sob
GROUP BY sob.status, sob.node_id
ORDER BY direction, sob.node_id, sob.status;
Starting to use Neo4j embedded with my JAVA web server. While saving the data the transaction was successful, but not able to visualize the data via browser.
Have tried sample Hello world from tutorial. And installed neo4j community edition, after pointing to DB and navigating to http://localhost:7474/browser/ i don't see any data.
Also, when i stop the application and run Cypher query via Java not getting any data.
Maven dependency used
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>2.3.1</version>
</dependency>
Sample code written
try {
Transaction tx = graphDb.beginTx();
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Hello, " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "World!" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
relationship.setProperty( "message", "brave Neo4j " );
tx.success();
}
DB path for embedded as well as server is same.
I do not know exact root of the issue. But I have checklist, that should be verified.
1) You application and Neo4j server should use same database. When you are creating embdedded database via GraphDatabaseFactory you are specifying database location. Same database location should be specified for Neo4j server in conf/neo4j-server.properties file (org.neo4j.server.database.location option).
2) You should NOT use database simultaneously in server and application. Database can be used only by one Neo4j instance at a time.
3) Use try-with-resource syntax for transactions. It is available in Java7 and later. Example:
try (Transaction tx = db.beginTx()) {
// do stuff
tx.success();
}
In this way transaction will be always closed, in any case (even if exception occurs during execution, or in beginTx()).
4) Ensure that your database is closed in “clean way”. In application it can be done via db.shutdown() method. Server can be stopped via bin/neo4j stop.
I have a issue populating v$session properties in oracle datasource ie after starting tomcat server my application would be using connection , now if I query DB with below query I should get a row from DB, currently I am not getting any row for 1st approach ,but 2nd approach works
select schemaname, osuser, machine, program
from v$session
where program = 'Test';
below are the configuration and tools I am using , any help regaring this is appriciated .
Thanks
1.Tomcate 6.0.35.3
2.Oracle version :Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
3.Spring and JPA
Approach 1:-
server.xml :
<Resource
name="jdbc/oraclepool"
auth="Container"
factory="oracle.ucp.jdbc.PoolDataSourceImpl"
type="oracle.ucp.jdbc.PoolDataSource"
description="main DB"
connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
connectionPoolName="UCPPool"
url="${db.url}"
user="${db.username}"
password="${db.password.encrypted}"
initialPoolSize="3"
minPoolSize="1"
maxPoolSize="5"
maxIdleTime="${db.maxIdleTime}"
inactiveConnectionTimeout="${db.inactiveConnectionTimeout}"
abandonedConnectionTimeout="${db.abandonedConnectionTimeout}"
timeToLiveConnectionTimeout="${db.timeToLiveConnectionTimeout}"
maxStatements="${db.maxOpenPreparedStatements}"
timeoutCheckInterval="${db.timeoutCheckInterval}"
connectionWaitTimeout="${db.connectionWaitTimeout}"
sqlForValidateConnection="${db.validationQuery}"
connectionProperties="v$session.program=Test;"
/>
Approach 2 :-
Added below code snippet in java class , it worked .
When I queried the db with below query , I was getting the row .
select schemaname, osuser, machine, program
from v$session
where program = 'Test';
Connection conn=null;
// set connection properties
Properties info = new java.util.Properties();
info.put("v$session.program", "Test");
// connect to database
Context context = new InitialContext();
PoolDataSourceImpl ds = (PoolDataSourceImpl)context.lookup("java:comp/env/jdbc/oraclepool");
((PoolDataSourceImpl)ds).setConnectionProperties(info);
conn = ds.getConnection();
Can anybody tell what is the issue with first approach
Thanks again .
I am trying to connect to one of my MySql Databases through a System DSN I set up. The DSN is set up correctly with my SSL certs, username, password, port, and the databases populate the DSN database drop down and the "Test" connection passes. I can't seem to get a connection in Java. I have spent 2 days looking through some examples on Stack but they all refer to an Access database and using JDBC-ODBC bridge which is no longer available in Java 8. I tried using UCanAccess with Jackcess but I have gotten no where. The code below is what I have been tinkering with the last few hours. I normally connect to MySql databases with PHP and receive result in JSON or directly with JDBC driver but for this project neither are really an option. Any ideas. I appreciate the help.
//String username = "<username>";
//String password = "<password>";
//String database = "<database_name>";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//Connect to cllients MySql Database
Connection conn = DriverManager.getConnection("jdbc:ucanaccess:" + database);
//Call VerifyLabel(<MAC>,<MODEL>); Call provided client
CallableStatement cStmt = conn.prepareCall("{CALL verify(?, ?)}");
//MAC
cStmt.setString(1, "mac address");
//model
cStmt.setString(2, "model");
cStmt.execute();
//Getting results from "Status" column
ResultSet rs1 = cStmt.getResultSet();
//Iterate results and print.
while (rs1.next()) {
System.out.println(rs1.getString("Status"));
}
//Close connection conn
rs1.close();
} catch (SQLException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
}
Using MySql Driver:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:"+ database);
also tried:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ database);
Error for MySql Driver:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
1) DSN is most commonly assocatiated with ODBC (and often with MS-Access). Hence all the links. ODBC is NOT required for a DSN.
2) Do NOT use Ucanaccess. Use J/Connector for mySQL.
3) Make sure you can communicate with mySQL from the command line. Then focus on getting a small "hello world" JDBC app to connect. Your second and third examples look OK. Be sure to check the mySQL logs for any warnings/errors.
Well, after an entire day of trying to get this to work and sleeping on it for a couple hours I finally got it to work. UCanAccess and mysql-connector did not work. The easiest thing since no other method of connecting to this clients database was acceptable was to push this application in Java 7 rather than 8. This allowed me to Coo=nnect to my DSN with no problems. I understand that this method is not the best solution but it is what is working flawlessly and efficiently. Also, instead of using some rigged up 3rd party libs and jars, I am able to use Connector/J. Thanks everyone for trying to help me. Just incase anyone else runs into this issue, this is how I made it work.
Develope app in Java 7 - not 8.
Set Up System DSN
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//You do not need to provide username or password if it is setup in DSN
Connection conn = DriverManager.getConnection("jdbc:odbc:"+ database);