Unable to connect to mySQL database using JSP - java

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 .

Related

How do I get a Connection to h2 database in swing

I wrote this code but it doesn't work.
It throws an error that says that this is not suitable Driver.
Can anyone explain what I am doing wrong?
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionUtil {
public static Connection getConnection() {
try {
Class.forName("org.h2.jdbc.Driver");
Connection con = DriverManager.getConnection("org.h2:database/javadb", "root", "");
return con;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
I used this URL for a connection to my DB "jdbc:h2:file:./database/mydatabase"

Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body

Here is the code for simple login Servlet in Eclipse which checks username and password from the existing table of database and take it to home page if exists or send to login page. When I run it on server and put information in login page it shows following error. can you help for that please. thank you.
1. Error to solve
root cause
java.lang.Error: Unresolved compilation problem:
Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body
com.loginapps.servlets.LoginServlet.doGet(LoginServlet.java:90)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
Coding
package com.loginapps.servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*** Servlet implementation class LoginServlet* #param <con>*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con;
PreparedStatement pst;
public void init(ServletConfig config) throws ServletException {
String dname = config.getInitParameter("drivername");
String uname = config.getInitParameter("username");
System.out.println(dname);
System.out.println(uname);
try{
Class.forName(dname);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb",uname,"");
}
catch(SQLException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String uname = request.getParameter("txtuname");
String pwd = request.getParameter("txtpwd");
session.setAttribute("username",uname);
try {
pst = con.prepareStatement("select * from users where username = ? and password = ?");
pst.setString(1,uname);
pst.setString(2,pwd);
ResultSet rs = pst.executeQuery();
if(rs.next()){
response.sendRedirect("home.jsp");
}
else {
response.sendRedirect("login.html");
}
}
catch(SQLException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
The error you posted:
Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body
Your catch block is the problem:
catch(ClassNotFoundException e){
e.printStackTrace();
}
ClassNotFoundException is a checked exception and is never thrown by the code inside your try block - see this page
I have removed catch(ClassNotFoundException e) in doGet method. It is working fine.
ClassNotFoundException is a checked exception and it will never occur in your doGet method code.

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.

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.

Connection Timeout while running sql procedure from servlet

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.

Categories