How to set class path and connect to DB2 using java - java

I don't know how to set the classpath in a java project.
This is the code that I run:
try { Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
} catch (ClassNotFoundException e) {
System.out.println("Please include Classpath Where your DB2 Driver is located");
e.printStackTrace();
return;
} System.out.println("DB2 driver is loaded successfully");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset=null;
boolean found=false;
try {
conn = DriverManager.getConnection("jdbc:db2:DB2PDBA","USERID","PASSWORD");
if (conn != null)
{
System.out.println("DB2 Database Connected");
}
else
{
System.out.println("Db2 connection Failed ");
}
and my Error is:
java.lang.ClassNotFoundException: com.ibm.db2.jdbc.app.DB2Driver

When we say put something within classpath, it means:
you should put the related jar files that your app needs to run
the entire application somewhere in your project.
Please follow the link below to create a DB2 application -> IBM Example about DB2
The only thing you need to do is to:
Add this into your project
change the credentials and db information
add the db2 jdbc jar file to your project

Related

Unable to connect to Phoenix using JDBC

I have a Hadoop Cluster set up with HBase and Phoenix and I'm trying to connect to Phoenix using JDBC, but I am sort of unable to get a successful connection.
I want to use JDBC to connect using Python 3.x but as for simple test purposes I set up a connection using Java in Eclipse.
I was originally using a 3rd party library (phoenixdb) for Python, but I started getting timeouts using this library (as my database grows). After this I changed some variables in the settings of my hbase-site.xml, to avoid timeout, but for some reason that didn't solve my problems using this 3rd party library.
So I tried to move on to JDBC and a Java project instead - at least for the testing.
I have the following Java code:
public class PhoenixTest {
static final String JDBC_DRIVER = "org.apache.phoenix.jdbc.PhoenixDriver";
static final String DB_URL1 = "jdbc:phoenix:https://xx.xx.xx.xx:8765/";
static final String DB_URL2 = "jdbc:phoenix:xx.xx.xx.xx:8765/";
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
System.out.println("Connecting to database..");
conn = DriverManager.getConnection(DB_URL);
st = conn.createStatement();
st.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
System.out.println("Finished!");
}
And with this piece of code and the client.jar it seems that the settings I changed are being recognized as the queries are taking 10 minutes (600.000 ms - which is what I changed it to from the default 60.000 ms) before the connection is closed unlike with the use of the phoenixdb library in which the connection is closed after using the default timeout (60.000 ms).
When I use DB_URL2 I get the following error:
java.sql.SQLException: org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=36, exceptions:
Thu Apr 06 11:13:35 CEST 2017, null, java.net.SocketTimeoutException: callTimeout=60000, callDuration=80236: row 'SYSTEM:CATALOG,,' on table 'hbase:meta' at region=hbase:meta,,1.1588230740, hostname=hadoopslave,16020,1490706604328, seqNum=0
Which doesn't match my timeout time of 600.000 ms. However when using DB_URL1 it seems to use the client.jar and the timeout time that I have set inside of the .jar (hbase-default.xml), which I have set to 300.000 ms, just to test which one is used. Using DB_URL1 I get the following error:
java.sql.SQLException: org.apache.hadoop.hbase.client.RetriesExhaustedException: Can't get the locations
Which I assume means that it can't find the IP.
However I never completely get a successful connection so I was hoping someone would have some suggestions to what is going wrong?
Thanks to #PaulBastide I managed to get a connection using the following link:
jdbc:phoenix:thin:url=http://<query_server>:<port>;serializa‌​tion=PROTOBUF
I also used the thin-client found together with the Phoenix distribution.

Unable to connect to Azure using JDBC (based upon the connection string and samples provide) due to SSL issue

Am getting the following error: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Connection reset by peer: socket write error."
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://XXXXX.database.windows.net:1433;"
+ "database=VDB;"
+ "user=XXX#VVV;"
+ "password=XXXX;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 2 * from Application";
statement = connection.createStatement();
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " "
+ resultSet.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the connections after the data has been handled.
if (resultSet != null) try {
resultSet.close();
} catch (Exception e) {
}
if (statement != null) try {
statement.close();
} catch (Exception e) {
}
if (connection != null) try {
connection.close();
} catch (Exception e) {
}
}
}
}
I'm only trying to do the "sample" connection snippet of code as referenced on the Azure site (which points to a MS entry), modified only to match my db and test table but without success.
Having reviewed all there is to know, I have:-
ensured that I'm using the right sqljdbc (I've tried all 4)
have the sqlauth.dll on the CLASSPATH
have set the sample up EXACTLY as shown; and incorporated the string that Azure offers.
I have tried various combinations of encrypt and trust without success. As I'm a newbie to Java and Azure, I'm reluctant and unsure how to fiddle with the JVM security settings.
I've proven that my machine can talk to the Azure database (through a VB ODBC connection); and I've tested with the firewall down.
Any thoughts?
I tried to reproduce the issue, but failed that I could access my SQL Azure Instance using the code which be similar with yours.
The difference between our codes is only as below, besides using the connection string of my sql azure instance.
Using the driver sqljdbc4.jar from the sqljdbc_4.0 link.
Using the code Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load MS SQL JDBC driver.
Not adding the sqlauth.dll file into the CLASSPATH.
Check my client IP which has been allowed by SQL Azure IP firewall.
Using the sql select 1+1 to test my code, and get the value 4 from code result.getInt(1).
That's fine for me. If you can supply more detals for us, I think it's very helpful for analysising the issue.
Hope it helps.

MySQL access from Hadoop MapReduce

I want to access MySQL database within my MapReduce program. I have a DBConnection class and I getConnection within the mapper class.The db.properties file is in place and with correct path mentioned in the DBConnection class.
Everytime I run the hadoop jar command I get error java.io.FileNotFoundException: db.properties (No such file or directory).
How can I resolve this?
Establishing DB connection in mapper:
Connection con = DBConnection.getConnection();
PreparedStatement pst = null;
String selectRows = "Select count(*) from sample";
Thanks
Try with this:
Prior Java 1.7:
InputStream input = YourClassName.class.getResourceAsStream("/db.properties");
try {
prop.load(input);
} catch (IOException ex) {
}finally{
input.close();
}
Java 1.7 and ahead:
try (InputStream input = YourClassName.class.getResourceAsStream("/db.properties")) {
prop.load(input);
} catch (IOException ex) {
}

connecting with Derby from within the java application

this program works fine when i connect the java db under the 'Services' tab in netbeans but when i try to open the executable jar file of the prog outside neatbeans it doesn't work at all. I want this java application to be accessible by multiple users as i wish to put it on the my local network so i figured that i need to connect to the Derby database in network mode....am i correct.?.....how should i fix this..?following is code snipet of my application
public void DoConnect() {
try {
/*
** Load the Derby driver.
** When the embedded Driver is used this action start the Derby engine.
** Catch an error and suggest a CLASSPATH problem
*/
Class.forName("org.apache.derby.jdbc.ClientDriver");
try {NetworkServerControl server = new NetworkServerControl();
server.start (null);}
catch(Exception e)
{
System.err.println(e.getMessage());
}
System.out.println(driver + " loaded. ");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
System.out.println("\n >>> Please check your CLASSPATH variable <<<\n");
}
try {
//CONNECT TO THE DATABASE
String host = "jdbc:derby://localhost:1527/Employee";
String uName = "admin";
String uPass = "admin";
//EXECUTE SQL QUERY AND LOAD RESULTSET
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM Workers";
rs = stmt.executeQuery(SQL);
//MOVE CURSOR TO FIRST RECORD AND GET DATA
rs.next();
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
//DISPLAY THE FISRT RECORD IN THE TEXT FIELD
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
IMHO it is bad practice to use a Derby database in network mode and to start the server in the same application. You combine all weaknesses of both world :
you cannot access the database from the outside (you server has to be local)
what happens if you server is allready running (if multiple executions on same node) ?
I think it works fine under Netbeans, because Netbeans is doing all the housekeeping for you : starting the server when you access to it via Netbeans interface, and closing it when closing Netbeans.
I think you should try the folowing :
start a server (manually) from outside of your application
remove the code for launching server from your app
(and do not forget to stop server when you have finished with it ...)
By the way I cannot understand what you mean by "not even starting" : if you start it from command line, you should have at least an error message ...
The way you've written the program there is no reason to meddle with the services tab. You should be able to just run (debug) the program directly in NB. Set a breakpoint, debug and step through it. When that works you can try to run from the command line.

How to read an sqlite database file in Java? (Package)

Okay i know i have to use the JDBC etc, but im not sure how to implement the jar into my code, i have a basic code to open the file etc, but how can i actually incorporate the sqlite jar alongside my java class file to be run anywhere?
So for example i have a folder with:
Test.class
new.db
sqlite.jar
In Test.class i have the basic connection and imports:
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:new.db");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT empname FROM employee");
while (resultSet.next()) {
System.out.println("EMPLOYEE NAME:"
+ resultSet.getString("empname"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
So how can i have this simple little script portable?
Thanks
Add the sqlite.jar to you classpath:
java -cp .;./sqlite.jar Anima
This should work. If not - please show your error message.
Edit
tested and verified. Create/Have a folder with the following content:
./project
Anima.class
sqlite.jar
then cd to folder project and do a
java -cp .;./sqlite.jar Anima
It works as expected on my machine.

Categories

Resources