Connection Timeout while running sql procedure from servlet - java

I want to run a procedure which takes approx 15 minutes to run in sql environment. Whereas when I am trying to run it using Servlet I am getting Network error(TCP error). I am using Http Server using ajp to transfer request to Tomcat server. This is my code. can anybody tell me what is going wrong here.
import com.itech.softensity.utils.Utils;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class JdbcServlet extends HttpServlet
{
protected static Logger logger = Logger.getLogger(JdbcServlet.class);
static final String jtdsurl = "jdbc:jtds:sqlserver://<server_name>;instance=<instance>;DatabaseName=<databasename>;socketTimeout=100000;socketKeepAlive=true";
static final String USER = "username";
static final String PASS = "password";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection con = null;
CallableStatement stmt = null;
ResultSet result =null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
logger.info("Connecting to database...");
con = DriverManager.getConnection(jtdsurl, "username","password");
logger.info("Creating statement...");
String sql = "exec populateMobRefLit";
stmt = con.prepareCall(sql);
stmt.setQueryTimeout(100000);
stmt.executeQuery();
logger.info("Executing stored procedure check new...");
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
logger.info("Procedure run successfully values: ");
}
catch (Exception e) {
try {
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
logger.info(Utils.stackTraceToString(e));
}
finally{
try {
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have tried it with JTDS driver as well as microsoft provided jdbc driver as the drivers have specific timeouts. I have tried Hibernate, I have tried Spring, but nothing works.

Related

Unable to connect Cassandra using jdbc driver

Hi I am trying to connect with Cassandra using jdbc driver. I am getting the following exception.
java.sql.SQLNonTransientConnectionException: Connection url must specify a host, e.g., jdbc:cassandra://localhost:9170/Keyspace1
at org.apache.cassandra.cql.jdbc.Utils.parseURL(Utils.java:190)
at org.apache.cassandra.cql.jdbc.CassandraDriver.connect(CassandraDriver.java:85)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.sub.cas.CqlJdbcTestBasic.main(CqlJdbcTestBasic.java:14)
My cassandra server is running fine and can be accessed from cql shell in windows 10 OS.
This is the java class that I have written.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CqlJdbcTestBasic {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra:/root/root#localhost:9160/hr");
String query = "SELECT empid, emp_first, emp_last FROM User WHERE empid = 1";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("empid"));
System.out.println(result.getString("emp_first"));
System.out.println(result.getString("emp_last"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = null;
}
}
}
}
I have gathered my jars from this url :: https://code.google.com/archive/a/apache-extras.org/p/cassandra-jdbc. Unable to find any possible solution. Please help.
Please, check if you have two slashes before your user name. According to
http://www.dbschema.com/cassandra-jdbc-driver.html

Null Pointer Exception in java servlets pages [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im very beginner in Java servlets... i have tried to connect servlet with database but NullPointerException
I tried to resolve this problem ,but no luck...
Error is
java.lang.NullPointerException
JDBCServlet.service(JDBCServlet.java:(42)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;//1
import java.sql.Connection;//2
import java.sql.SQLException;
import java.sql.Statement;//3
import java.sql.ResultSet;//4
public class JDBCServlet extends HttpServlet {
Connection con;
Statement st;
ResultSet rs;
String sql;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("JDBC Servlet Invoked");
//1st step: load JDBC MySql Drivers
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Drivers Loaded");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2nd Step: create a connection
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webtech1", "root", "123456");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sql = "select * from user";
try {
st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("firstName"));
System.out.println(rs.getString("lastName"));
System.out.println(rs.getString("email"));
System.out.println(rs.getString("password"));
System.out.println(rs.getString("createdate"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please put null checks on your con,st,rs objects. And also double check your mysql connection string.
You have initialised String sql twice. One as a property and one as a local variable i.e.
String sql = "select * from user";
Later, you are calling sql (an instance variable) which is indeed of null value, which causes null pointer exception. You just need to remove String declaration from the body of your service method.

Unable to connect to mySQL database using JSP

I'm trying to establish a connection to my database using the following servlet: (the work is done in the doGet method)
package demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Connect")
public class Connect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Connect() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
out.println("Unable to load database.");
return;
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/jakesdb", "root", "sixTeen58");
} catch (SQLException e) {
out.println("Unable to connect to the database.");
return;
}
//// Connected to database. do some work here ////////////
out.println("Connected to the database!");
///////////////////////////////////////////////////////////
try {
conn.close();
} catch (SQLException e) {
out.println("Unable to close connection to database.");
}
}
}
However, I am always getting hung up at
try {
conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/jakesdb", "root", "sixTeen58");
} catch (SQLException e) {
out.println("Unable to connect to the database.");
return;
}
I have verified using sql workbench that the username (root) and password (sixTeen58) are correct, and the port is indeed 3306. I have mysql-connector-java-5.1.36.zip in my libraries and it's linked properly. I'm not sure what is going on but every time I just see "Unable to connect to the database" when I run the page.
Any idea what I'm doing wrong?
You did a minor mistake. You need colon : instead of . at database URL of getConnection method. Change like:
"jdbc:mysql://localhost:3306/jakesdb" // Use : instead of .

Establishing connection between Android app and Oracle DB using JDBC driver

I am having trouble establishing a connection between my app and an Oracle DB using JDBC drivers.
Host Oracle ver.: Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
.Jar jdbc drivers I have tried: ojdbc5.jar, ojdbc6.jar, ojdbc14.jar, all from oracle itself.
I have granted the application the permission in the manifest.
<uses-permission android:name="android.permission.INTERNET" />
I get absolutely no response, nothing in the logcat. The SQL statement has no effect on the remote DB.
I can connect the remote DB with the same login credentials on my machine with SQL Plus and have all the privileges.
Code from MainActivity.java
package testapp.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.sql.ResultSet;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
super.onCreate(savedInstanceState);
ConnectOra db = new ConnectOra();
ResultSet rs = db.getResult();
ArrayList<String> list = new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString(1));
System.out.println(rs.getString(1));
}
} catch (Exception e) {
System.out.print(e);
}
}
public void btn(View view) {
startActivity(new Intent(MainActivity.this, MainActivity.class));//Just to refresh the mainact.
}
}
Code from ConnectOra.java:
package testapp.myapplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.util.Log;
public class ConnectOra {
private Connection conn;
private Statement stmt;
public ConnectOra() throws ClassNotFoundException {
try {
System.out.println("in try");
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#103.A.B.C:15210/mdb";
this.conn = DriverManager.getConnection(url,"XXX","pw");
this.conn.setAutoCommit(false);
this.stmt = this.conn.createStatement();
} catch(SQLException e) {
Log.d("tag", e.getMessage());
}
}
public ResultSet getResult() throws SQLException {
ResultSet rset = stmt.executeQuery("select * from emp;");
System.out.println(rset+"");
stmt.close();
return rset;
}
}
The selected answer works and my code works too.
Android cant work with ojdbc5.jar, ojdbc6.jar as they require some Java SE components not available on Android. So, we have to use ojdbc14.jar since its older than ojdbc5.jar and ojdbc6.jar and doesn't require advance Java components, this also means that only the basic functions are there with ojdbc14.jar.
With ojdbc14.jar you might have to set "SQLNET.ALLOWED_LOGON_VERSION=8" in sqlnet.ora on the remote host running the DB. This will allow older clients to connect to newer DB otherwise it throws the error ORA-28040: No matching authentication protocol.
It is also vital to close the Connection and Statement after the SQL statements have been executed, else the changes aren't saved in the actual remote DB.
Can you try out this code and post the error log. Also a word of caution, you really shouldnt do this, you should have an application sever like this to manage connections to Oracle DB. But if you wanna play it unsafe, try out this code :
String driver = "oracle.jdbc.driver.OracleDriver"; //
String serverName = "localhost";
String portNumber = "1521";
String db = "XE";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":"
+ db; // connectOracle is the data
// source name
String user = "system"; // username of oracle database
String pwd = "root"; // password of oracle database
Connection con = null;
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
Class.forName(driver);// for loading the jdbc driver
System.out.println("JDBC Driver loaded");
con = DriverManager.getConnection(url, user, pwd);// for
// establishing
// connection
// with database
Statement stmt = con.createStatement();
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
while (true) {
try {
socket = serverSocket.accept();
System.out.println("Connection Created");
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
// System.out.println("message: " +
// dataInputStream.readUTF());
ResultSet res=stmt.executeQuery("select * from person");
while(res.next()){
System.out.println(res.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And read again, this is not recommended.

How to store the fetched MySQL data into Optaplanner-examples

I have created a MySQL database with entries similar to nurse roster, i have generated these entries to be in XML format using below code.
package com.jdbcxml;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.w3c.dom.Document;
class EmployeeDAO
{
private Connection conn = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public EmployeeDAO()
{
String url = "jdbc:mysql://50.62.23.184:3306/dbname";
String userId = "root";
String passWord = "";
try
{
conn = DriverManager.getConnection(url, userId, passWord);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void finalize()
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Document getCustomerList()
{
Document doc = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
doc = JDBCUtil.toDocument(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return doc;
}
public String getCustomerListAsString()
{
String xml = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
xml = JDBCUtil.toXML(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return xml;
}
public static void main(String argv[]) throws Exception
{
EmployeeDAO dao = new EmployeeDAO();
String xml = dao.getCustomerListAsString();
System.out.println(xml);
Document doc = dao.getCustomerList();
System.out.println(doc);
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//out.write(doc);;
//out.close();
}
}
Now i need this data to be saved in Optaplanner-examples-->data-->nurserostering-->unsolved folder.
Also after doing this will the optaplanner be able to write a solution to the passed data to some file so that i can display those results on my webpage.
Why you storing the data you get from database to xml file? It will be more efficiently feed the data to optaplanner solver and get the best solution. Read my answer from your previous question HERE

Categories