Solved

Java Servlet connection to mysql

Posted on 2003-11-15
3
1,717 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

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…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

772 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

15 Experts available now in Live!

Get 1:1 Help Now