Solved

Java Servlet connection to mysql

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 46
maven module vs maven project 3 112
American Express @Work site and Java 4 93
dao vs facade design patterns 2 68
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

737 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