Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8034159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T01:55:27+00:00 2026-06-05T01:55:27+00:00

I want to access mysql database on my localhost via a java servlet through

  • 0

I want to access mysql database on my localhost via a java servlet through my android app. I was able to access database through a java class but when tried the same code in my android activity, it’s not working. Below is the code for my java servlet, java class through which I successfully accessed my database and android code which isn’t working. In my LogCat log I am getting all the logs till BufferedReader class. Also please tell me which widget can I use in Android to display the response string. I know presently my response string will contain HTML code but that doesn’t matter I just want to know if I am able to access my database. Thank You.
Java Servlet Code:

package org.spark.servlet;

import java.io.IOException;
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet2
 */
@WebServlet("/HelloServlet2")

public class HelloServlet2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void service(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException{
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Hello World</title></head>");
        out.println("<body>");
        out.println("<h1>Hello World2</h1>");
        // connecting to database
        Connection con = null;    
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con =DriverManager.getConnection ("jdbc:mysql://localhost:3306", "root", "password");
            stmt = con.createStatement();
            rs = stmt.executeQuery("Use servlettest");
            rs = stmt.executeQuery("SELECT * FROM servlet");
            // displaying records
            while(rs.next()){
                out.print(rs.getObject(1).toString());
                out.print("\t\t\t");
                out.print(rs.getObject(2).toString());
                out.print("<br>");
            }
        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
          } catch (ClassNotFoundException e) {
              throw new ServletException("JDBC Driver not found.", e);
            } finally {
                try {
                    if(rs != null) {
                        rs.close();
                        rs = null;
                    }
                    if(stmt != null) {
                        stmt.close();
                        stmt = null;
                    }
                    if(con != null) {
                        con.close();
                        con = null;
                    }
                } catch (SQLException e) {}
            }
            out.println("</body></html>");  
            out.close();
        }
    }

Java Class Code:

package org.ProjectEuler;
import java.io.*;
import java.net.*;
public class HelloServlet {
    public static void main( String [] args ) {

        try {

            URL url = new URL("http://localhost:8080/HelloServlet/HelloServlet2");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);

            BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream()));
            out.write("username=javaworld\r\n");
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream()));

            String response;
            while ( (response = in.readLine()) != null ) {
                System.out.println( response );
            }
            in.close();
        }
        catch ( MalformedURLException ex ) {
            // a real program would need to handle this exception
        }
        catch ( IOException ex ) {
            // a real program would need to handle this exception
        }
    }
}

Andriod Code:

package org.spark.mysqltest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;


public class MySqlTestActivity extends Activity {
    EditText test;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("checked","checked");
        System.out.println("check");
        Log.d("checked2","checked2");
        test = (EditText) findViewById(R.id.mtv);
        Log.d("checked3","checked3");
        setContentView(R.layout.main);
        Log.d("checked4","checked4");

        try {
            Log.d("checked5","checked5");

            URL url = new URL("http://localhost:8080/HelloServlet/HelloServlet2");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            Log.d("checked6","checked6");
            BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream()));
            Log.d("checked7","checked7");
            out.write("username=javaworld\r\n");
            Log.d("checke","checke");
            out.flush();
            Log.d("check","check");
            out.close();
            Log.d("chec","chec");
            BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream()));
            Log.d("che","che");
            String response;
            while ( (response = in.readLine()) != null ) {
                System.out.println( response );
              //  test.setText(response);
                Log.d("checked8","checked8");
            }
            Log.d("checked9","checked9");
            in.close();
        }
        catch ( MalformedURLException ex ) {
            // a real program would need to handle this exception
        }
        catch ( IOException ex ) {
            // a real program would need to handle this exception
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T01:55:28+00:00Added an answer on June 5, 2026 at 1:55 am

    First problem: you aren’t specifying an encoding when you create your InputStreamReader. That means you’ll use the platform default encoding, which may not be the encoding used to create the web response. (Likewise when you’re creating the request.)

    Second problem: you’re ignoring any exceptions:

    catch ( MalformedURLException ex ) {
        // a real program would need to handle this exception
    }
    catch ( IOException ex ) {
        // a real program would need to handle this exception
    }
    

    My guess is that an exception is being thrown, but you have no idea because you’ve swallowed those exceptions without even logging. At the very least, add logging in here and I think you’ll see what’s going wrong. You should almost never have empty catch statements like this.

    Do you have any reason for using the low-level API like this, by the way? Using a good high-level HTTP client library is likely to make your life a lot simpler.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to access a MySQL database from Java, but remote connection is disabled
I want to access a MySQL database and I want to read+write data from+to
I want to access an online MySQL database in order to retrieve and manipulate
I want to use JDBC to access a MySQL database. What or will an
I am currently able to register Jabber User ID from http://localhost:5280/xmpp-http-bind/register/ but i want
I want to access to database mysql, I read that we can define the
I want to access a MySQL database directly from JavaScript code in an HTML
I want to take back up of mysql database table in sql file through
I want to have access to a MySQL database (my website database) from an
I have a MySQL database set up on 000webhost.com. I want to access the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.