I'm begginner in cassandra , I'm trying to connect to cassandra database and insert some rows in netbeans but I have error under the import : package com.datastax.driver.core does not exist any solutions ?
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
public class CassandraConnection {
public static void main(String args[])
{
System.out.println("Cassandra Java Connection");
Cluster cluster;
Session session;
//Connect to the cluster and Keyspace ecommerce
cluster=Cluster.builder().addContactPoint("localhost").build();
session=cluster.connect("ecommerce");
System.out.println("Inserting Data in Cassandra");
session.execute("INSERT INTO products (pdt_id, cat_id, pdt_name, pdt_desc, price, shipping) VALUES (001,104, 'Danby 0.7 cu. ft. Microwave Oven', 'Capacity of 0.7 cu. ft.10 different power levels', 54.00, 'Expedited')");
String pdtid = null, pdtname = null, pdtdesc = null;
float price = 0;
ResultSet resultset=session.execute("select * from products where pdt_id=005");
for(Row row :resultset){
pdtid = Integer.toString(row.getInt("pdt_id"));
pdtname = row.getString("pdt_name");
pdtdesc = row.getString("pdt_desc");
price = row.getFloat("price");
System.out.println("Product ID: " + pdtid);
System.out.println("Name: " + pdtname);
System.out.println("Description: " + pdtdesc);
System.out.println("Price: "+ price);
}
cluster.close();
}
}```
It looks like you haven't configured the dependencies correctly so it can't find the Java driver package. As Andreas also pointed out, it appears you're using old code which has been refactored in Java driver v4.x.
Since your new to Cassandra, I recommend having a look at https://www.datastax.com/dev where we have free code samples and interactive tutorials using Katacoda.
For example, learn CRUD operations on Cassandra with the Java driver in this hands-on tutorial which launches a Cassandra cluster + a dev environment where you can code -- all in a single browser window: https://www.datastax.com/dev/scenario/datastax-java-driver-apache-cassandratm-quickstart. All free with no login required.
You can also have a look at the code samples on Astra and learn how to develop apps using REST API, GraphQL API or Document API without any Cassandra knowledge. Cheers!
try to add maven dependency (or jar file to your project)
<!-- https://mvnrepository.com/artifact/com.datastax.cassandra/cassandra-driver-mapping -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-mapping</artifactId>
<version>3.11.0</version>
</dependency>
Related
I am trying to connect to mongo collection to perform some load tests on it. but getting some error.
Can anyone please help me with the same?
DatabaseName and CollectionName I have stored in user defined variables.
Code I am using:
import com.mongodb.client.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
// Connect to the client
try {
MongoClient mongoClient = MongoClients.create("mongodb://<userName>:<password>#prodoperationalcluster1-shard-00-00-pri.z1wts.mongodb.net:27017,prodoperationalcluster1-shard-00-01-pri.z1wts.mongodb.net:27017,prodoperationalcluster1-shard-00-02-pri.z1wts.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-44ekvq-shard-0&authSource=admin&retryWrites=true&w=majority");
MongoDatabase database = mongoClient.getDatabase(vars.get("databaseName"));
MongoCollection<Document> collection = database.getCollection(vars.get("collectionName"));
vars.putObject("collection", collection);
return "Connected to " + vars.get("collectionName");
}
catch (Exception e) {
SampleResult.setSuccessful(false);
SampleResult.setResponseCode("500");
SampleResult.setResponseMessage("Exception: " + e);
}
In order to help you with the same we need to know what the same MongoDB java drivers you have in JMeter Classpath because if for example you downloaded the same driver .jar and BSON jar is not the same you will get the same error.
You can see Jar Hell for the same
Also ensure that the versions of MongoDB Java Client drivers and the version of MongoDB on the server side are the same because you cannot use the versions which are not the same for the same.
Check out MongoDB Performance Testing with JMeter article for more information on the same.
I am trying to connect to a SQLite database on my local device (Ubuntu).
my setup is VS Code with Maven
The error
java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/idir/embag/chek/Data/Checks.sql
Database.java, connect method
public void Connect() {
String AbsolutePath = new File("").getAbsolutePath();
path = "jdbc:sqlite:"+ AbsolutePath + DATABASE_PATH + DATABASE_NAME ;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(path);
if (conn != null){
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
}
catch(Exception e){
System.out.println(e.toString());
}
}
Maven pom.xml
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
Module-info.java
requires java.sql;
requires mysql.connector.java;
What I tried
+3 hours of search with no hope
I fixed the problem by removing the MySQL dependency as pointed out by the previous responses .
Added to the Module-info.java:
requires org.xerial.sqlitejdbc;
Also added this to pom.xml:
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/services/java.sql.Driver</resource>
</transformer>
Don’t mix database engines
You are asking your MySQL driver to make a connection using a string meant for SQLite.
MySQL and SQLite are two entirely separate different database engines. So your code makes no sense.
By the way…
In modern Java, there is no need to call Class.forName. JDBC drivers are now automatically loaded via the Java SPI facility.
Generally best to separate your code for configuring the database connection info from the code that accesses the database. Have the first produce a DataSource object that is passed into the second.
summary (After running SQL INSERT INTO statement the data is not view-able in the MS Access table without closing and reopening the database)
What it is:
Simple Java class using Ucanaccess diver to insert rows into an existing table in MS Access database file.
To create the condition:
Open the MS Access database file. Create and save a table with four columns. Name the table "TestExportRows". In addition to the code below, you will need to add to the Java app a user GUI with a button that runs the method. Run the java app, press the button which runs the SQL statement within "public void testExportSingleRow() method". Open table in MS Access database. No records visible. Close and reopen the MS Access database and open the table. Records are now visible. Also, cannot compact and repair database until the Java app is closed.
I've searched long and hard for an answer to this one. I also spent a great deal of time eliminating potential causes. I believe I am closing the connection and statement properly. I need to have this work without the need to reopen the MS Access database or shutting down the Java app.
Here's the code:
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author petehahn
*/
public class Trash {
public void testExportSingleRow() {
try {
File dir1 = new File("..");
String path1;
path1 = dir1.getCanonicalPath();
String pathTarget = path1 + "\\" + "Playground.accdb";
File dbTargetFile = new File(pathTarget);
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String url = "jdbc:ucanaccess://" +dbTargetFile +";showschema=true";
Connection dbConnection = DriverManager.getConnection(url);
String sqlString = "INSERT INTO TestExportRows(Item,Category,Aluminum,Copper) "
+"VALUES ('Column 1','Column 2','Column 3','Column 4')";
Statement sqlInsertStatement = dbConnection.createStatement();
sqlInsertStatement.executeUpdate(sqlString);
dbConnection.commit();
dbTargetFile = null;
sqlInsertStatement.close();
dbConnection.close();
} catch (IOException | ClassNotFoundException | SQLException ex) {
Logger.getLogger(DbTestExportToAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
NetBeans 8.0.2 64bit
MS Access 2013 32bit
Windows 8.1 64bit
ucanaccess version 2.0.9.3
Pete, this is an absolutely known outcome, because
you're writing on the access file without passing through the microsoft jet engine.
So Access can't know you're updating the file until it's reopened.
I can't understand what's your real issue or concern.
Ucanaccess can help you to manipulate access files(in all OS), but it can't integrate itself with the Access client.
Notice that a practice with an uncontrolled concurrent access to Access file from different processes (java through UCanAccess and Access client) is STRONGLY INADVISABLE.
i want to query existdb from Java. i know there are samples but where can i get the necessary packages to run the examples?
in the samples :
import javax.xml.transform.OutputKeys;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.xmldb.EXistResource;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.modules.XMLResource;
where can i get these ?
and what is the right standard connection string for exist-db? port number etc
and YES, i have tried to read the existdb documentation, but those are not really understandable for beginners. they are confusing.
All i want to do is write a Java class in eclipse that can connect to a exist-db and query an xml document.
Your question is badly written, and I think you are really not explaining what you are trying to do very well.
If you want the JAR files as dependencies directly for some project then you can download eXist and get them from there. Already covered several times here, which JAR files you need as dependencies is documented on the eXist website and links to that documentation have already been posted in this thread.
I wanted to add, that if you did want a series of simple Java examples that use Maven to resolve the dependencies (which takes away the hard work), then when we wrote the eXist book we provided just that in the Integration Chapter. It shows you how to use each of eXist's different APIs from Java for storing/querying/updating etc. You can find the code from that book chapter here: https://github.com/eXist-book/book-code/tree/master/chapters/integration. Included are the Maven project files to resolve all the dependencies and build and run the examples.
If the code is not enough for you, you might also want to consider purchasing the book and reading the Integration Chapter carefully, that should answer all of your questions.
i ended up with a maven project and imported some missing jars (like ws.commons etc) by manually installing them on maven.
the missing jars i copied from the existdb installation path on my local system.
then i got it to work.
from: http://exist-db.org/exist/apps/doc/devguide_xmldb.xml
There are several XML:DB examples provided in eXist's samples
directory . To start an example, use the start.jar jar file and pass
the name of the example class as the first parameter, for instance:
java -jar start.jar org.exist.examples.xmldb.Retrieve [- other
options]
Example: Retrieving a Document with XML:DB
import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;
import javax.xml.transform.OutputKeys;
import org.exist.xmldb.EXistResource;
public class RetrieveExample {
private static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
/**
* args[0] Should be the name of the collection to access
* args[1] Should be the name of the resource to read from the collection
*/
public static void main(String args[]) throws Exception {
final String driver = "org.exist.xmldb.DatabaseImpl";
// initialize database driver
Class cl = Class.forName(driver);
Database database = (Database) cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
Collection col = null;
XMLResource res = null;
try {
// get the collection
col = DatabaseManager.getCollection(URI + args[0]);
col.setProperty(OutputKeys.INDENT, "no");
res = (XMLResource)col.getResource(args[1]);
if(res == null) {
System.out.println("document not found!");
} else {
System.out.println(res.getContent());
}
} finally {
//dont forget to clean up!
if(res != null) {
try { ((EXistResource)res).freeResources(); } catch(XMLDBException xe) {xe.printStackTrace();}
}
if(col != null) {
try { col.close(); } catch(XMLDBException xe) {xe.printStackTrace();}
}
}
}
}
On the page http://exist-db.org/exist/apps/doc/deployment.xml#D2.2.6 a list of dependencies is included; unfortunately there is no link to this page on http://exist-db.org/exist/apps/doc/devguide_xmldb.xml (should be added);
The latest xmldb.jar documentation can be found on http://xmldb.exist-db.org/
All the jar files can be retrieved by installing eXist-db from the installer jar; the files are all in EXIST_HOME/lib/core
If you work with a maven project, try adding this to your pom.xml
<dependency>
<groupId>xmldb</groupId>
<artifactId>xmldb-api</artifactId>
<version>20021118</version>
</dependency>
Be aware that the release date is 2002.
Otherwise you can query exist-db via XML-RPC
I am new to cassandra and moven. I was trying to write a simple java program in eclipse that uses cassandra java driver to connect to a cassandra node I have setup.
I found this repository https://github.com/datastax/java-driver but I have no idea what I should do with it. Can anyone give me step by step instructions for getting the driver and creating a simple eclipse project that uses the driver.
Start Eclipse (make sure eclipse has maven, I used eclipse KEPLER)
Create a new eclipse project (Under the Maven folder select "Maven Project")
Give the project a name / group-id / artifact-id
Open pom.xml and then click on the actual pom.xml tab.
Add the dependency shown on github, my pom file ended up looking like this.
And finally write a class to do some stuff with the driver, the below creates a keyspace and a column family.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class App
{
public static void main( String[] args )
{
Cluster cluster = Cluster.builder()
.addContactPoints("127.0.0.1")
.build();
Session session = cluster.connect();
String cqlStatement = "CREATE KEYSPACE myfirstcassandradb WITH " +
"replication = {'class':'SimpleStrategy','replication_factor':1}";
session.execute(cqlStatement);
String cqlStatement2 = "CREATE TABLE myfirstcassandradb.users (" +
" user_name varchar PRIMARY KEY," +
" password varchar " +
");";
session.execute(cqlStatement2);
System.out.println("Done");
System.exit(0);
}
}
Also check this answer out for CRUD operations with the driver.