how to setup cassandra java driver with eclipse - java

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.

Related

package com.datastax.driver.core does not exist

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>

Java, sqlite3 since command line troubleshooting

my name is Omar
i am following the instructions in this webpage https://www.tutorialspoint.com/sqlite/sqlite_java.htm in order to compile a sample program of java conected with sqlite3.
sample program
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
try {
// Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
i downloaded the sqlite connector sqlite-jdbc-3.7.2.jar but according to the webpage above, i Added the address of downloaded jar file sqlite-jdbc-(VERSION).jar in my class path(the same class path of mysql address connector) and place the sqlite-jdbc-3.7.2.jar in C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext just like mysql connector driver.
but i got bad results when i try to run it in command line
"No suitable driver found for jdbc: sqlite: test.db"
i run java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC with the sqlite-jdbc-3.7.2.jar in the same folder in command line but i got bad results too.
"No suitable driver found for jdbc: sqlite: test.db"
Where sqlite-jdbc-3.7.2.jar connector should be placed according to connect java and sqlite just as myql do?
anyhelp is appreciated
thank you in advance
Omar
You should download and use the newest SQLite driver 3.27.2.1 from this site: https://bitbucket.org/xerial/sqlite-jdbc/downloads/
I tried it with 3.7.2 and got the same error. But with 3.27.2.1 it works well.

Jenkins SQLServer Choice Parameter - Retrieve data from database

I am trying to get data from SQL Server database table and show it as part of choice parameter as part of a Jenkins Job Build Parameters that I am trying to setup.
I am trying to figure out how to use Extensible Choice for this.
The Choice provider I used is "System Groovy Choice Parameter"
import groovy.sql.Sql
import com.microsoft.sqlserver.jdbc.SQLServerDriver
def output = []
def configuration = [
'dbInstance' : 'servername',
'dbPort' : 0000,
'dbName' : 'dbName',
'dbUser' : 'dbUser',
'dbPass' : 'dbPass'
]
def sql = Sql.newInstance("jdbc:sqlserver://${configuration.dbInstance}:${configuration.dbPort};"
+ "databaseName=" + configuration.dbName,
configuration.dbUser, configuration.dbPass,
'com.microsoft.sqlserver.jdbc.SQLServerDriver')
String sqlString = "SELECT * FROM dbTable"
sql.eachRow(sqlString){ row -> output.push(row[0])
}
return output.sort()
Below is the error I see. Which I understand I see because the jdbc driver is not present. I downloaded the driver from the link below:
https://www.microsoft.com/en-us/download/details.aspx?id=11774
I followed the instructions as to where it should be unzipped to as mentioned in the instructions.
I saw that the CLASSPATH variable is missing, so i went ahead and created the Environment variable with path: "C:\Program Files\sqljdbc_6.0\enu\sqljdbc.jar"
Error: unable to resolve class com.microsoft.sqlserver.jdbc.SQLServerDriver
How do i make sure that the script runs successfully and returns all the data to Extensible Choice. If there is anyother way to do this, I am open to suggestions.
Thank you very much
To resolve the issue I had to copy the "sqljdbc4.jar" file to the following location "C:\Java\jdk1.8.0_92\jre\lib\ext" since that is the path where the JAVA searches for the external jars. Use 4th version for the file which will have 4 in the file name as above as that is version Jenkins supports.

MySql Driver Not Loading In Java

When I use the following line,
Class.forName("com.mysql.jdbc.Driver");
//Sets up database connection
connect = DriverManager.getConnection("jdbc:mysql://www.papademas.net/tickets?"
+ "user=root&password=jamesp");
statement = connect.createStatement();
String sql = "INSERT INTO JReimTicketer (dateIssued, ticketName, issuerName,"
+ " issuerDepartment, ticketDescription, activity) "
+ "VALUES (SYSDATE(),'"+ticketName+"', '"+issuerName+"', "
+ "'"+issuerDepartment+"', '"+ticketDescription+"', "
+ " '"+activity+"')";
my program stops, and it doesn't seem like it loads the driver. I've downloaded it, so I'm not sure why it's not working. Any help would be appreciated.
Firstly if your are using jdbc 4.0, you don't require
Class.forName("com.mysql.jdbc.Driver");
to load driver as it it auto-loaded when you call
DriverManager.getConnection();
If you have specified mysql jar in your class path, the problem must be in your url. So kindly check your URL/Username/Password
Also, if you are getting exception,please post stacktrace
Your code seems to be correct. And I think you're right. Things aren't missing from Front-End but Back-End. So, before you compile your code, you need to put MySQL Connecter jar (mysql-connector-java-x.x.xxx-bin.jar) file in your Java Buildpath Path. Do it before you compile and run the code.

Derby Embedded with jar file throw database not found exception

Hi i created a derby embedded db with a simple java application.
When test run on eclipse it run perfectly.And then i export as a runnable jar file .Run via cmd
gives exception database not found..!!!
public class Main {
public static void main(String[] args) throws SQLException {
final String driver="org.apache.derby.jdbc.EmbeddedDriver";
final String url="jdbc:derby:db/testdb";
try {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url);
//connection.createStatement().execute("create table channels(channel varchar(20),topic varchar(20))");
// connection.createStatement().execute("insert into channels (channel,topic) values('hbo','action')");
// System.out.println("saved");
PreparedStatement preStmt=connection.prepareStatement("select * from channels");
ResultSet set=null;
set=preStmt.executeQuery();
while(set.next()){
System.out.print(set.getString(1));
System.out.println(set.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Errors
Exception in thread "main" SQL Exception: Database 'db/testdb' not found.
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Sourc
My need is when i run jar file on other java enabled pc it must run..!!!
i already tried on other pc it gives me same error..!
How can i make database created....!!
Someone know please help..!
After building the jar, go to the project folder and copy the dist folder. Move it to a new location and also copy the database folder inside the new dist folder you just moved. That should do it; most of the time when people have problem with Derby it is because of Java file paths.
The magic about Derby schema creation is via jdbc url itself.
Let me use Java 8 Derby to elaborate. Run cmd.
Add Derby related to environment path:
cd D:\Project\derbydb
set JAVA_HOME=C:/Program Files/Java/jdk1.8.0_92
set DERBY_HOME=C:/Program Files/Java/jdk1.8.0_92/db
set PATH=%PATH%;%DERBY_HOME%/bin
Execute ij command to work with Derby.
D:\Project\derbydb>ij
ij version 10.11
ij> CONNECT 'jdbc:derby:testdb;create=true';
When url="jdbc:derby:testdb;create=true", [D:\Project\derbydb\testdb] folder is automatically initialized from where it is run. Then, we can use Derby normally like any other databases.
ij> CREATE TABLE cart (
item VARCHAR(50),
price DECIMAL (10,5),
dt TIMESTAMP,
primary key (item)
);
ij> select * from cart;
After Derby repository exists, then we can connect it from anywhere.
C:\Users\oraclesoon>ij
ij version 10.11
ij> CONNECT 'jdbc:derby:D:\\Project\\derbydb\\testdb';
ij> select * from cart;

Categories