SSL DB2 connection failed - java

I am trying to connect to a DB2 database using SSL on IBM Bluemix.
When I first tried to connect without SSL, it doesn't work. After reading the documentation, I have realized that it connects to the database with SSL enabled.
I tried using the following code to get it connect to the database:
public boolean connect() {
try {
String url = "jdbc:db2://" + serverName + ":" + port + "/" + dbName+
":securityMechanism=9";
connection = DriverManager.getConnection(url, userName, passWord);
st = connection.createStatement();
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
}
return false;
}
Still I am not too sure on how to use the SSL certificate provided with the code above.
I tried searching for examples but most of the explanations are either unclear or used for another database system.

If you are using Liberty, a datasource is generated for you, and you can look it up using jndi.
#Resource(lookup = "jdbc/mydb")
private DataSource myDataSource;
Connection c = myDataSource.getConnection();
"mydb" is the name of the SQLDB service
https://developer.ibm.com/bluemix/2014/02/07/java-db2-10-minutes/

According to the SQLDB documentation, If you use the latest com.ibm.db2.jcc.DB2Driver with the JDBC connection, the current SSL certificate is bundled with the driver and does not need manually installing.
The following snippet shows you how to use the connection details available from VCAP_SERVICES to connect to SQLDB over SSL.
public class SSLTEST {
/**
* #param args
*/
public static void main(String[] args) {
String ServerName = "hostname or IP address";
int PortNumber = 50001;
String DatabaseName = "SQLDB";
String user = "your_user_id_from_VCAP_SERVICES";
String userPassword = "your_password_from_VCAP_SERVICES";
java.util.Properties properties = new java.util.Properties();
properties.put("user", "user ID that has access to SQLDB");
properties.put("password", "password for the user ID that has access to SQLDB");
properties.put("sslConnection", "true");
String url = "jdbc:db2://" + ServerName + ":"+ PortNumber + "/" +
DatabaseName + ":" + traceFileLocation + ";";
java.sql.Connection con = null;
try
{
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
}
catch ( Exception e )
{
System.out.println("Error: failed to load Db2 jcc driver.");
}
try
{
System.out.println("url: " + url);
con = java.sql.DriverManager.getConnection(url, properties);
if (con != null) {
System.out.println("Success");
} else {
System.out.println("Failed to make the connection");
}
con.close();
}
catch (Exception e)
{
if (con != null) {
try {
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
e.printStackTrace();
}
}

finally i use datasource to connect to the database.
Context ic = new InitialContext();
DataSource db = (DataSource)context.lookup("jdbc/MyDatabase");

Related

android with JDBC. createStatement() does not exist?

I am trying to create a connection with a database using JDBC on my android project. I am following a tutorial which says to import a jar and then create a connection in the activity. Everything is ok, but in the connection statement i get an error
Cannot resolve method 'createStatement()'
if I try to get into the reference of the method, it says
cannot find decleration to go to
This method comes from the jar i have imported? (jtds-1.3.1)
Is there anything else i am missing here?
#Override
protected String doInBackground(String... params)
{
Connection con;
String usernam = params[0];
String passwordd = params[1];
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
// Change below query according to your own database.
String query = "select * from owner where mail = '" + usernam.toString() + "' and password = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + database + ";user=" + user+ ";password=" + password + ";";
connection = (Connection) DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
I got the same problem with the close() method
All you've got to do is specify the class name fully:
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/product","root","");
No need for a cast, and the error you're reporting will now go away, as the compiler will be looking for the method in the right class.
Or just rename your own class Connection.

connecting a java app to external microsoft sql server 2012

I have created a SQL server 2012 database. I need to connect to the database by using Java app created on another pc. this is my code but I cannot connect to the database, and I get error: "Login failed. The login is from an untrusted domain and cannot be used with Windows Authentication." (my code is working when both Java app and SQL server running on the same PC).
Appreciate your help.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String jdbcUrl = "jdbc:sqlserver://THINKPADPC:1433;databaseName=TestDB;integratedSecurity=true;";
conn = DriverManager.getConnection(jdbcUrl);
Have you tried sql server authentication. And pass username and password.
If you tryin windows authentication then it might be taking credentials from your(java) machine which has not been giving access on the hosted sql server machine.
Please Try this Connection and Change the ip, db , sa and password.
public class ConnectionClass {
String ip = "192.168.0.131";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "Andro";
String un = "sa";
String password = "Admnsql1~";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}`enter code here`
}

Cannot connect Java to external mysql database

Hello i am currently building a programm that register users to mysql database. Everything works fine on localhost but when i try to connect to external database it gives me an error such as this below.
I have granted all privileges to the user in the database i am trying to acess and also i have the driver installed. Any ideas??
My code:
private void createEventListenerDBProperties() {
dbSubmitBtn.addActionListener((ActionEvent e) -> {
if (dbDriverChooser.getSelectedItem().equals("com.mysql.jdbc.Driver")) {
driver = (String) dbDriverChooser.getSelectedItem();
port = dbPortField.getText();
host = "jdbc:mysql://" + hostField.getText() + ":" + port + "/";
db = dbnameField.getText();
dbuser = dbUsernameField.getText();
dbpassword = new String(dbPasswordField.getPassword());
}
}
});
}
private Connection instanciateDB() {
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(host + db, dbuser, dbpassword);
System.out.println("Connection Established");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Connection not Established");
JOptionPane.showMessageDialog(Project2.this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
return con;
}
I think your way to connect is wrong. Instead of this:
con = DriverManager.getConnection(host + db, dbuser, dbpassword);
try this:
con = DriverManager.getConnection(host + db + "?user=" + dbuser + "&password=" +dbpassword);
Check this out, it may be useful.
http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html

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

Class not found loading JDBC org.postgresql.Driver

I'm working on a web project and I recently installed postgres 9.1.1
The postgresql server is up and running. I can connect via psql as usual and everything is loaded and properly saved from a dump of the db I made from 8.5.
So I also downloaded the JDBC4 driver for 9.1 postgres version here:
http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz
I added it to the java build path using the project properties via eclipse.
This is the code I use to provide db connection to other classes (i.e. it's a singleton, I get a new connection only if the existing is either closed or null, from one object at a time only)
public abstract class DBConnection {
private static Connection connection = null;
public static void connect() {
try {
if (connection == null) {
String host = "127.0.0.1";
String database = "xxxxx";
String username = "xxxxx";
String password = "xxxxx";
String url = "jdbc:postgresql://" + host + "/" + database;
String driverJDBC = "org.postgresql.Driver";
Class.forName(driverJDBC);
connection = DriverManager.getConnection(url, username,
password); //line firing the class not found exception
} else if (connection.isClosed()) {
connection = null;
connect();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
public static Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
connect();
return connection;
}
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE,
null, e);
return null;
}
}
#Override
public void finalize() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
}
As I wrote in the title when I run the project and a class asks for a connection to this class I always get a Class Not Found Exception, Since it apparently can't load the org.postgresql.Driver.class The driver is located in a subfolder of the project ~/lib/org.postgresql-9.1-901.jdbc4.jar and as I said added to the build path via eclipse project properties.
I'm also providing a sample query to let see the usual behavior of my classes to access the DBConnection:
public static final User validateUserCredentials(String id, String pswd) {
Connection connection = DBConnection.getConnection();
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null");
Statement stmt = null;
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd);
String sql = "Select * from fuser where id = '" + id + "'";
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery(sql);
Logger.getLogger(Credentials.class.getName())
.log(Level.SEVERE, sql);
resultset.next();
String password = resultset.getString("pswd");
if (pswd.equals(password))
return new User(id, pswd);
} catch (SQLException ex) {
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
if (stmt != null)
stmt = null;
if (resultset != null)
resultset = null;
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
connection = null;
}
}
return null;
}
I'm working on a web project and I recently installed postgres 9.1.1
...
I added it to the java build path using the project properties via eclipse.
That's the wrong way. That JAR has to be dropped straight in /WEB-INF/lib folder of the web project without fiddling with the Build Path in the project's properties. That folder is standard part of webapp's runtime classpath.
Unrelated to the concrete problem: you've a major design flaw in your DBConnection class. You've declared Connection as static which essentially makes your connection not threadsafe. Use a connection pool and never assign the Connection (nor Statement nor ResultSet) as a class/instance variable. They should be created and closed in the very same try-finally block as where you're executing the query. Further you've there also a SQL injection hole. Use PreparedStatement instead of concatenating user-controlled variables in the SQL string.
See also:
JDBC MySql connection pooling practices to avoid exhausted connection pool
Get database connection from a connection pool
Am I Using JDBC Connection Pooling?
Add this dependency in your pom:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1203-jdbc4</version>
</dependency>
The first thing I'd do is unpack the jar and confirm that the driver is really in there as org.postgresql.Driver. I notice when looking at jarfinder and related sites that there isn't a Postgres 9.x jar containing org.postgresql.Driver.

Categories