Link to home
Start Free TrialLog in
Avatar of iakix
iakix

asked on

Java Servlet connection to mysql

Can someone give me a simple source code of java servlet for connecting to mysql database?
Avatar of El_Pollo_Diablo666
El_Pollo_Diablo666

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)
        {
        ;
        }
    }
    }
Avatar of iakix

ASKER

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?
ASKER CERTIFIED SOLUTION
Avatar of jimmack
jimmack

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial