unable run restfull webservice in java while connecting to sqlsever - java

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

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 get a String from a field

I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful

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.

NullPointerException in Web Services Client (eclipse)

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?

Java Eclipse JDBC Oracle: DriverManager.getConnection stuck

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

Categories