What should be the connection string while using CQL jdbc driver - java

What should be the connection string while using CQL jdbc driver?
Will I be able to find a proper/complete example for CQL using CQL JDBC driver in Java online?

You'll need the cql jar from the apache site.
Here's the basic test I used after entering data via CLI (using sample from wiki):
public class CqlJdbcTestBasic {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra:root/root#localhost:9160/MyKeyspace");
String query = "SELECT KEY, 'first', last FROM User WHERE age=42";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("KEY"));
System.out.println(result.getString("first"));
System.out.println(result.getString("last"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = null;
}
}
}
}
The user/password (root/root) seems arbitrary, just be sure to specify the Keyspace (MyKeyspace)
Note, 'first' is quoted in the query string because it is an CQL keyword

You may also try using the cassandra-jdbc driver from http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/.
Alternatively using the following maven dependency:
<dependency>
<groupId>org.apache-extras.cassandra-jdbc</groupId>
<artifactId>cassandra-jdbc</artifactId>
<version>1.2.1</version>
</dependency>

Related

ClassNotFoundException: Google Cloud SQL with MySQL/SocketFactory

I'm trying to connect my Java code to a db I've created in Google Cloud SQL, but I'm getting ClassNotFound and SQLException errors: -
java.lang.ClassNotFoundException: com.google.cloud.sql.mysql.SocketFactory
java.sql.SQLException: No suitable driver found for jdbc:mysql
I'm also getting a NullPointerException in code, in the getAllFilms() method at the line below, which I'm assuming is because the code isn't making a db connection: -
ResultSet rs1 = stmt.executeQuery(selectSQL);
Things I've done so far: -
Tested the Google Cloud SQL db credentials, through a client connection
Reviewed related posts, particularly [this one][1]
Been through the Google documentation
Added MySQL and Socket Factory Connector(j8) JARs to my project dependencies
Unfortunately I'm still unable to resolve. Hopefully someone can help. I've attached my Java code below. Thanks in advance...
Film oneFilm = null;
Connection googleSqlConnection = null;
Statement stmt = null;
String url = "jdbc:mysql:///<dbname>?<cloudSqlInstance>&socketFactory=com.google.cloud.sql.
mysql.SocketFactory&user=<user>&password=<pword>";
public FilmDAO() {
}
private void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.google.cloud.sql.mysql.SocketFactory");
} catch (Exception e) {
System.out.println(e);
}
try {
googleSqlConnection = DriverManager.getConnection(url);
stmt = googleSqlConnection.createStatement();
} catch (SQLException se) {
System.out.println(se);
}
}
private void closeConnection() {
try {
googleSqlConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<Film> getAllFilms() {
ArrayList<Film> allFilms = new ArrayList<>();
openConnection();
try {
String selectSQL = "select * from films limit 50";
ResultSet rs1 = stmt.executeQuery(selectSQL);
while (rs1.next()) {
oneFilm = getNextFilm(rs1);
allFilms.add(oneFilm);
}
stmt.close();
closeConnection();
} catch (SQLException se) {
System.out.println(se);
}
return allFilms;
}
[1]: https://stackoverflow.com/questions/53693679/connecting-to-google-cloud-sql-with-java
Have you added the Cloud SQL JDBC SocketFactory and mysql-connector-java to your pom.xml?

How to get a String from a field

I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful

cannot exexute SQL query wirh OJDBC and Oracle DB (but full working with posgtres JDBC and Postgres DB)

I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}

combination of Oracle database and in-memory database in java program

I am going to enhance the performance of my program. For this purpose I am going to implement some parts of my program to be done in memory instead of database. I dont know which one is better in this regards, in-memory database or normal java data structure.For in-memory database I considered Tentimes from oracle and H2. So another question would be which solution is better for around 100 million records of data on single machine for single user? Also another question would be is the old way of database connection works fine in this way? Here is the connection that I used for oracle, What is the appropriate Driver for this purpose.
public static Connection getConnection(){
//If instance has not been created yet, create it
if(DatabaseManager.connection == null){
initConnection();
}
return DatabaseManager.connection;
}
//Gets JDBC connection instance
private static void initConnection(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
String connectionUrl = "jdbc:oracle:thin:#localhost:1521:" + dbName;
DatabaseManager.connection =
DriverManager.getConnection(connectionUrl,"****","****");
}
catch (ClassNotFoundException e){
System.out.println("Oracle driver is not loaded!");
System.exit(0);
}
catch (SQLException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (Exception e){
}
}
public static ResultSet executeQuery(String SQL) throws SQLException
{
CachedRowSetImpl crs = new CachedRowSetImpl();
ResultSet rset = null ;
Statement st = null;
try {
st = DatabaseManager.getConnection().createStatement();
rset = st.executeQuery(SQL);
crs.populate(rset);
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}finally{
rset.close();
st.close();
}
return crs;
}
public static void executeUpdate(String SQL)
{
try {
Statement st = DatabaseManager.getConnection().createStatement();
st.executeUpdate(SQL);
// st.close();
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
Regards.

How to connect JDBC to tns oracle

I can connect from plsql to database using tns file
Now I want to connect to the database from my Java using JDBC.
What I tried:
I search google and I find that I have to using this connection String:
"jdbc:oracle:thin:#//host:port))/tnsfile)";
My computer name is myPC
The port that is written in the tnsfile is 5151
So I tried this connection String
"jdbc:oracle:thin:#//myPC:5151))/tnsfile"
but I got this Exception
java.sql.SQLRecoverableException: IO ERROR: SO Exception was generated
What am I doing wrong?
How to connect my JDBC to the database using tns file?
You have to set a property named oracle.net.tns_admin to point to the location of the folder containing your tnsnames.ora file. Then you specify the entry from that file after the # sign in your DB URL. Check example below. You can find more information here: Data sources and URLs - Oracle Documentation
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("oracle.net.tns_admin", "C:/app/product/11.2.0/client_1/NETWORK/ADMIN");
String dbURL = "jdbc:oracle:thin:#ENTRY_FROM_TNSNAMES";
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbURL, "your_user_name", "your_password");
System.out.println("Connection established");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT dummy FROM dual");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stmt != null) try { stmt.close(); } catch (Exception e) {}
if (conn != null) try { conn.close(); } catch (Exception e) {}
}
}
}
Example entry from tnsnames.ora file:
my_net_service_name=
(DESCRIPTION=
(ADDRESS=(some address here))
(CONNECT_DATA=
(SID=some_SID_name)))
Where my_net_service_name string is what you have to subsitite for ENTRY_FROM_TNSNAMES from my Java example.
Rather than hard code the path to tnsnames.ora, better to find it from the environment:
public static void setTnsAdmin() {
String tnsAdmin = System.getenv("TNS_ADMIN");
if (tnsAdmin == null) {
String oracleHome = System.getenv("ORACLE_HOME");
if (oracleHome == null) {
return; //failed to find any useful env variables
}
tnsAdmin = oracleHome + File.separatorChar + "network" + File.separatorChar + "admin";
}
System.setProperty("oracle.net.tns_admin", tnsAdmin);
}
Try the following:
System.setProperty("oracle.net.tns_admin", PATH_TO_TNSNAMES.ORA);
Class.forName ("oracle.jdbc.OracleDriver");
dbUrl = "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST="+IPHOST+")(PORT="+PORT+"))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME="+DBNAME+")))"
conn = DriverManager.getConnection(dbUrl, USERNAME, PASSWORD);
Be sure to have the latest version of ojdbc.jar

Categories