?
Solved

Java Servlet connection to mysql

Posted on 2003-11-15
3
Medium Priority
?
1,740 Views
Last Modified: 2013-11-24
Can someone give me a simple source code of java servlet for connecting to mysql database?
0
Comment
Question by:iakix
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 

Expert Comment

by:El_Pollo_Diablo666
ID: 9758040
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DBServlet extends HttpServlet
    {
    private Connection con;
    private PrintWriter out;

    public void init(ServletConfig conf) throws ServletException
    {
    super.init(conf);
    try
        {
        class.forName("com.mysql.jdbc.Driver");
        con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/NomDeVotreBase", "VotreIdMySql", "VotreMdpMySql");
        }
    catch(Exception e)
        {
        System.out.println(e);
        }
    }

    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
    res.setContentType("text/html");
    try
        {
        out = res.getWriter();
        out.println("<html><head><title>");
        out.println("JDBC Servlet");
        out.println("</title></head><body>");

        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM essai");
        out.println("<UL>");

        while(rs.next())
        {
        out.println("<LI>" + rs.getString("nom"));
        }
        out.println("</UL>");
        rs.close();
        stmt.close();
        }
    catch(SQLException e)
        {
        out.println("Exception SQL");
        }
    catch(IOException e)
        {
        }

    out.println("</body></html>");
    out.close();
    }

    public void destroy()
    {
    try
        {
        con.close();
        }
    catch(SQLException e)
        {
        ;
        }
    }
    }
0
 

Author Comment

by:iakix
ID: 9768407
i got this errors:



C:\ck\Connections.java:16: <identifier> expected
        class.forName("com.mysql.jdbc.Driver");
             ^
C:\ck\Connections.java:16: '{' expected
        class.forName("com.mysql.jdbc.Driver");
                                              ^
C:\ck\Connections.java:17: <identifier> expected
        con =DriverManager.getConnection ("jdbc:mysql://localhost:8080/touchscreen", "ck", "ck");
            ^
C:\ck\Connections.java:19: 'catch' without 'try'
    catch(Exception e)
    ^
C:\ck\Connections.java:14: 'try' without 'catch' or 'finally'
    try
    ^
C:\ck\Connections.java:25: illegal start of expression
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    ^
C:\ck\Connections.java:70: ';' expected
    }
    ^
C:\ck\Connections.java:70: '}' expected
    }
     ^
8 errors

can u tell me how to edit this?
0
 
LVL 15

Accepted Solution

by:
jimmack earned 180 total points
ID: 9769965
Several problems with the previous comment.

1) You shouldn't override service() unless you really know what you are doing.  You should normally only override doPost() or doGet().  If you don't care which HTTP method will be used to open the page, have one of these call the other (as I have shown below)

2) You only want the database connection for this connection, so don't create it when the servlet is initialised (in the init() method), then destroy it when the servlet is unloaded (in the destroy() method).  Create it when you need it.  If the servlet grows in complexity (or expected hit frequency), you should consider using a connection pool.

3) class.forName should have been Class.forName

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DBServlet extends HttpServlet
{
    private Connection con;
    private PrintWriter out;


    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/NomDeVotreBase", "VotreIdMySql", "VotreMdpMySql");
        }
        catch (Exception e)
        {
            System.out.println(e);
        }

        res.setContentType("text/html");
        try
        {
            out = res.getWriter();
            out.println("<html><head><title>");
            out.println("JDBC Servlet");
            out.println("</title></head><body>");

            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM essai");
            out.println("<UL>");

            while (rs.next())
            {
                out.println("<LI>" + rs.getString("nom"));
            }
            out.println("</UL>");
            rs.close();
            stmt.close();
        }
        catch (SQLException e)
        {
            log("Exception SQL" + e.toString());
        }

        out.println("</body></html>");
        out.close();

        try
        {
            con.close();
        }
        catch (SQLException e)
        {
            log("SQLException " + e.toString());
        }
    }


    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        doGet(req, res);
    }
}
0

Featured Post

Application Discovery Service in AWS

In the era of the cloud, customers migrating away from their existing on-premise infrastructure. This requires lots of planning, strategies, and effort to identify their existing resources and determine how best to migrate.  Datacenter migrations happen in four phases -

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
A solution for Fortify Path Manipulation.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month14 days, 1 hour left to enroll

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question