How to connect JDBC to tns oracle - java

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

Related

Android studio can't connect to database in Azure sql server

I am using android studio to develop an application and using Azure Sql Server to host my database. The problem is I was able to connect to my database on SQL server but it has an error of Object not found in my database.
I found out that it might be connecting to my master database instead of the database I want it to connect to. Is there any solution to solve the problem?
package com.example.lenovo.testing1;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
public class ConnectionClass {
String hostName = "haozailai.database.windows.net";
String dbName = "haozailai";
String user = "username";
String password = "password";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String ConnURL;
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://haozailai.database.windows.net:1433;database=haozailai;user=username;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
}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 conn;
}
}
Picture of my database structure
I tried to connect my sqlserver via java jdbc and did not reproduce your issue.
I can connect to my application db successfully.
My test code:
import java.sql.*;
public class Test {
public static final String url = "jdbc:sqlserver://***.database.windows.net:1433;database=***;user=***password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
public static final String name = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection conn = null;
public static PreparedStatement pst = null;
public static Statement stmt = null;
public static ResultSet rs = null;
public static void main(String[] args) {
try {
String SQL = "select * from dbo.Student";
Class.forName(name);
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close() {
try {
conn.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After some research, I found out it is because of your connect url.
You need to modify your connect url :
jdbc:jtds:sqlserver://haozailai.database.windows.net:1433/<your application db name> ...
You could refer to the pages below for more details.
https://sourceforge.net/p/jtds/discussion/104389/thread/a672d758/
how to connect sql server using JTDS driver in Android
Update answer:
I have made a slight adjustment to your connect URL and can connect to my application database normally.
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
Notice that remove the database=*** and add "/<your database name>" after your host string.
Please refer to the above code and try again.Any concern, please let me know.
Hope it helps you.
I know this answer is waay too late, but I found this video that totally works: https://www.youtube.com/watch?v=WJBs0zKGqH0
The thing is, you have to download a jtds jar, the guy in the video says where you can get it from and also, you need to add "jtds" before "sqlserver" in connection url and edit the way the 'databe' is written in the connection url, like this:
jdbc:jtds:sqlserver://serverName.database.windows.net:portNr:DatabaseName=dbName;user=....

How to connect to Oracle DB using JDBC connection with out opening Oracle in my machine

Hi Below is the code I wrote for connecting to Oracle DB using JDBC connection and return some values. But this code establish the connection and returns the result if I am opening the oracle toad in my machine.
But when the oracle toad is closed and try to run this code, it will not connect.
Please let me knwo how to connect to oracle DB with out opening the oracle toad manually.
package library;
import java.io.IOException;
import java.sql.*;
public class DBAutomationConnection {
public static void main(String args[]) throws ClassNotFoundException, IOException, SQLException {
DBAutomationConnection dbconn = new DBAutomationConnection();
//Connection conn = dbconn.DBConnection1();
dbconn.DBConnection1("select * from employee where empid='test123'","ROLE_NAME");
}
public void DBConnection1(String query, String colName)throws IOException, ClassNotFoundException{
Connection connection = null;
Statement stmt = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:oracle:thin:#//testhostname:1528/ServiceName", "XXAAA_U", "Jw9S");
System.out.println("Connection successful: " +connection);
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//String UserID = rs.getString("USER_ID");
String UserID = rs.getString(colName);
System.out.println(UserID);
}
} catch (SQLException e ) {
System.out.println("Could not execute query.");
//JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
} catch (SQLException e) {
System.out.println("Could not connect to the database");
}
}
You should initialize Oracle TNS-Listener Service from your OS settings>services. You may need to check your tns configuration.
you need to install ORACLE client in your system to connect oracle remotely.
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
Do you have Oracle Thin driver installed in your system? This link can guide you.

JDBC SQL Server Exception

I’m trying to connect a Java program with MS SQL SERVER 2012 but Java throws the exception: java.lang.ClassNotFoundException.
I understand that the problem often is a result of that the CLASSPATH is not set up correctly for the driver. I have followed the directions from Oracle to add a CLASSPATH, but I still get the same exception. When I type “echo %CLASSPATH%" in the command prompt I get a correct response. What have I missed?
Code:
import java.sql.*;
public class JDBCTest {
public static void main(String[ ] args) throws SQLException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch(Exception e) {
System.out.println("Can't find database driver: " + e);
}
}
}
The runtime environment for your application may not contain the appropriate jar file.
The path that you have checked is only for your console environment. The application classpath is different from this.
Try this
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=YourDBName;user=UserName;Password=YourPassword"
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
....
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
make sure that you download the driver jar file and put it at the right place
If Class.forName fails it is a problem of classpath.
try this code to check your classpath:
String classPath = System.getProperty("java.class.path");
String userDir = System.getProperty("user.dir");
System.out.println("Working Directory:");
System.out.println("\t"+userDir);
System.out.println("Classpath:");
String[] paths = classPath.split(";");
for (String path : paths) {
File pathFile = new File(path);
String check = pathFile.exists()?"OK ":"NOT-FOUND ";
System.out.println("\t"+check+path);
}
First of all download sqljdbc4.jar from here
Put this .jar in Your /WEB-INF/lib folder. (Check if this file appears from your eclipse's lib if not then Refresh Your Project)
And then run Your Project.

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.

how to install JDBC and how to use it to connect to mysql?

i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?
below is the codes that i used
import java.sql.*;
public class Test1
{
public static void main (String[] args)
{
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
System.out.println("Connecting database...");
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}
}
And below is the Response that i get
Cannot connect to database server
Update # 3
C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Test1.main(Test1.java:12)
Closing the connection.
You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.
You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial
On the other hand, if you are using an IDE such as Netbeans or Eclipse you can add the jar file as a resource to the project.
You certainly have JDBC problems, but the exception isn't telling you that. Read it again:
Exception in thread "main" java.lang.NoClassDefFoundError: Test1
Caused by: java.lang.ClassNotFoundException: Test1
It's your Test1.class that it can't find, not the JDBC driver.
You should not be copying anything into the jre/lib/ext directory. That's for library extensions, not JDBC JARs. It wasn't meant as a crutch for people who don't understand how CLASSPATH works.
I'd write it more like the following. Those close methods will come in handy.
When I run it on my machine, adding the MySQL JDBC JAR to my CLASSPATH, I get the following result:
C:\java -classpath .\mysql-connector-java-5.1.6-bin.jar; persistence.utils.DatabaseUtils
product: MySQL
version: 5.1.24-rc-community
major : 5
minor : 1
Here is the source code:
package persistence.utils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseUtils
{
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/contacts";
public static final String USERNAME = "contacts";
public static final String PASSWORD = "contacts";
public static void main(String[] args)
{
Connection connection = null;
try
{
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : URL);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
connection = getConnection(driver, url, username, password);
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("product: " + metaData.getDatabaseProductName());
System.out.println("version: " + metaData.getDatabaseProductVersion());
System.out.println("major : " + metaData.getDatabaseMajorVersion());
System.out.println("minor : " + metaData.getDatabaseMinorVersion());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Connection connection = null;
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
'I am trying to install JDBC'
You don't have to install JDBC. It is part of the JDK & JRE.
Try putting your .jar file in the classpath.
The library that contains the Driver (net.sourceforge.jtds.jdbc.Driver) needs to be on the classpath.
Assuming you start your application with
java Test1
then simply do
java -cp .;driver.jar Test1
where 'driver.jar' should be exchanged with the filename (relative or full path) of your database driver lib.
EDIT
A classpath tutorial will exceed the comments section below this question. Please take a cup of coffee and look at this page. It will most likely help you to continue.

Categories