I am fairly new java web services and I trying to use it to access an oracle database. What my project is trying to do is take the input of a zip code and return the information from the database.
I got a web services client working for an animal type using this tutorial and I am trying to take what I learned from that for my project:
http://javapapers.com/web-service/java-web-service-using-eclipse/
Here is my the code for the main class I am using:
package com.zipws.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//import javax.jws.WebService;
//import javax.jws.soap.SOAPBinding;
//import javax.jws.soap.SOAPBinding.Style;
public class ZipWebServiceImpl {
public String cityFinder(String zip) {
Connection con = null;
String str = "";
try{
String user = "IVRDEVUSR";
String pass = "voice001";
String url = "jdbc:oracle:thin:#UIQ-UAT-ORA-02:1521/IVRST01";
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement();
ResultSet rsZip = stmt.executeQuery("SELECT *FROM ZIPLOC WHERE ZIP = " + zip);
while(rsZip.next()){
if(zip.equals(rsZip.getString("ZIP"))){
str = rsZip.getString("CITY");
}
else{
str = "Zip code for city not found!";
}
}
rsZip.close();
stmt.close();
}
catch(SQLException e){
//System.out.println("Connection Failed.");
str = "connection failed";
}
catch(ClassNotFoundException cnfe){
//System.out.println("Unable to load driver.");
str = "Unable to load driver";
}
finally{
try{
con.close();
}
catch(SQLException e){
//System.out.println("Failed to close connection.");
str = "Failed to close connection.";
}
}
return str;
}
}
The web services client classes were generated by Eclipse which I learned to do from the tutorial earlier. When I run the client and enter a zipcode to try to invoke the above class, it returns a NullPointerException and I do not know why. Can anyone possibly explain why?
You should check in the finally block if 'con != null'. Otherwise even in cases the driver could not be loaded you are trying to close the connection which can never succeed.
Debug the method and check what exception occurs. Is maybe the oracle driver missing in the classpath?
Related
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
I am writing this because I created a simple Login GUI App to test sqlite database as I am a student of Database Systems and new to it, I used java through eclipse, whenever I run the Application this message
java.sql.SQLException path to c:user//path does not exist
Error Screenshot
I have searched a lot on google but couldn't find the solution there is a similar question on stackoverflow but there were not enough answer related to my problem, I want to know how to change the code to make the Application work and connect to database?
Any help will be much appreciated.Thanks
Here is the code:
package dbms;
import java.sql.*;
import javax.swing.*;
public class dbConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\chusm\\workspace\\DBMS\\SQlite\\DBMS.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!!!");
return conn;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
It looks like you've got some weird whitespace action going on in your url (between "jdbc:sqlite" and "C:"
Please copy paste this exact code in your project and run it (I only removed the weird whitespace, the rest is exactly like your code)
package dbms;
import javax.swing.*;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
public class StackOverflowExample {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\chusm\\workspace\\DBMS\\SQlite\\DBMS.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!!!");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public static void main(String[] args) {
Connection connection = dbConnector();
}
}
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.
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
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