Solved

Java Servlet connection to mysql

Posted on 2003-11-15
3
1,720 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
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 45 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

910 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

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now