Java Eclipse JDBC Oracle: DriverManager.getConnection stuck - java

while I'm able to connect and query an oracle database using Oracle SQLDeveloper, I'n not able to do the same from a test java application:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#myhost:1521/mysid"; //SID
//String url = "jdbc:oracle:thin:#myhost:1521:myservice"; //service
String usr = "myuser";
String pwd = "mypassword";
System.out.print("Before DriverManager...");
con = DriverManager.getConnection(url, usr, pwd);
if (con == null)
{
System.out.print("Connection is null");
}
else
{
System.out.print("Connection OK");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT count(*) FROM mytable");
while(rs.next()) {
System.out.print(rs.getInt(1));
//System.out.println(rs.getString(2));
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Some system details:
OS: Mac OS X 10.9.4
Java Version: 1.7
Eclipse: Kepler (64bit)
Oracle Client: instantclient_10_2
After some unsuccessful tentatives, I decided to copy exactly the same JDBC driver used by SQLDeveloper (using show package content). I've copied it under my project folder/lib. And then I added the jar to the build path.
When I run the application on my mac it just remain stuck after printing "Before DriverManager..."
If I run the same application on a colleague windows machine it works fine and print the count results.
I'm really out of options, and I'm starting to think there's some issue with my machine java permission. Is it possible? Any idea where I should look for?
Any help is appreciated.
Regards
Stefano

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=....

unable run restfull webservice in java while connecting to sqlsever

I am trying to call a web service that returns data from my sqlsever database in json format
This my code to get data from sqlsever and convert it to a json.
Here a function getAllDataJson() returns a String value of the result.
This is working fine when i call it to display as
SqlDatabase db = new SqlDatabase();
System.out.println(db.getAllDataJson);
but it is not working when i call it from a webservice (This webservice configuration is also fine, i used this webservice to return json String before there it worked fine)
if i combine these both it is showing error in the function getAllData() (which is in the below return code)
at the line:
rs = stmt.executeQuery("select * from persons");
it is showing nullPointerException
It is showing this error
The same error is not there if run it as java application, it is only there when i am running on webservice
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class SqlDatabase {
private static final String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=FIRST;integratedSecurity=true;";
Connection con = null;
Statement stmt = null;
private void connectToDb(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
} catch (SQLException e) {
System.out.println("error occured at Database Connection");
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
}
}
void closeDb(){
try{
if(con != null){con.close();}
if(stmt!=null){stmt.close();}
}catch(SQLException e){
System.out.println("error occured while closing Database Connection");
}
}
public ResultSet getAllData(){
ResultSet rs = null;
connectToDb();
try {
rs = stmt.executeQuery("select * from persons");
} catch (SQLException e) {
System.out.println("error occured while getting data");
}
return rs;
}
public String getAllDataJson() throws JSONException{
ResultSet rs = getAllData();
if(rs == null){return null;}
JSONArray jArray = new JSONArray();
JSONObject json = null;
//data to json
try {
while(rs.next()){
for(int i = 1;i<=rs.getMetaData().getColumnCount();i++){
json = new JSONObject();
json.put(rs.getMetaData().getColumnName(i), rs.getString(i));
}
jArray.put(json);
}
} catch (SQLException e) {
System.out.println("near Json");
}
return jArray.toString();
}
}
See at your DB host URL dbc:sqlserver://localhost:1433
It says localhost. Means it will always checks for DB server installed in the same machine where it is getting executed.
Check the DB server and web server are installed in the same machine. If not instead localhost you better to use IP address. Replace the localhost with the IP of DB server running.
Assume the IP of the system where DB server is running is 182.10.10.45 then
dbc:sqlserver://182.10.10.45:1433

The service class "WBSer_RwCnt.Rw_Count" does not comply to one or more requirements of the JAX-RPC 1.1 specification

package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.

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.

java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver

I am really new to JAVA but need to call a SQL Server function which I have been given access to.
I have built a JAVA call into a pl/sql function and am successfully calling it from one of my environments. When I move to another environment I get the error
ORA-29532: Java call terminated by uncaught Java exception: java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver
I have researched this to death and checked the correct installation of JAVA which seems fine but I'm obviously missing something. I need to somehow trace what is different on this environment, the fact that it runs in the other envionmnet proves that the class is correct so it has to be a config issue.
JAVA Class
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.net.Socket;
import java.io.IOException;
public class xxiceHJ
{
protected static String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
protected static String DB_URL = "jdbc:sqlserver://999.999.99.99:1433";
protected static String USER = "xxxx";
protected static String PWD = "xxxxx123$";
public static String getOrderStatus (String OrderNumber) throws SQLException, Exception
{
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
String Message = null;
String WarehouseId = "01";
try
{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
//Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PWD);
cs = conn.prepareCall("{call usp_get_order_status(?,?,?)}");
cs.setString(1, WarehouseId);
cs.setString(2, OrderNumber);
cs.setString(3, Message);
rs = cs.executeQuery();
//if prodeure return a value
if (rs.next())
{
Message = rs.getString(1);
}
//Clean-up environment
rs.close();
cs.close();
conn.close();
// }
// catch (SQLException se)
// {
// //Handle errors for JDBC
// cfFileNumber = "SQLException" + se.toString();
// se.printStackTrace();
// }
// catch (Exception e)
// {
// //Handle errors for Class.forName
// cfFileNumber = "Exception" + e.toString();
// e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if (rs!=null)
{
rs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (cs!=null)
{
cs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (conn!=null)
{
conn.close();
}
}
catch (SQLException se)
{
se.printStackTrace();
}
}
return Message;
}
}
The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer. If the drivers are not listed in your CLASSPATH variable, you receive the following error message when you try to load the driver:
java.lang.ClassNotFoundException: com/microsoft/jdbc/sqlserver/SQLServerDriver
The JDBC driver is not part of the Java SDK. If you want to use it, you must set the classpath to include the sqljdbc.jar file or the sqljdbc4.jar file. If the classpath is missing an entry for sqljdbc.jar or sqljdbc4.jar, your application will throw the common "Class not found" exception.
The sqljdbc.jar file and sqljdbc4.jar file are installed in the following location:
\sqljdbc_\\sqljdbc.jar
\sqljdbc_\\sqljdbc4.jar
The following is an example of the CLASSPATH statement that is used for a Windows application:
CLASSPATH =.;C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc.jar
The following is an example of the CLASSPATH statement that is used for a Unix/Linux application:
CLASSPATH =.:/home/usr1/mssqlserverjdbc/Driver/sqljdbc_4.0/enu/sqljdbc.jar
You must make sure that the CLASSPATH statement contains only one Microsoft JDBC Driver for SQL Server, such as either sqljdbc.jar or sqljdbc4.jar.
For more information, please see:
http://support.microsoft.com/kb/313100
http://msdn.microsoft.com/en-us/library/ms378526.aspx
first Please download correct sql driver and then check your are using correct connection driver as per operating system. then once you have to test your connection if its working fine then you will go to next .
so please check this url
microsift sql server driver for linux
https://msdn.microsoft.com/en-us/library/hh568451(v=sql.110).aspx
my sql server driver for linux
https://dev.mysql.com/downloads/connector/j/5.0.html

Categories