L
L
Luka Tarkhnishvili2016-06-09 15:07:24
MySQL
Luka Tarkhnishvili, 2016-06-09 15:07:24

How to connect MySQL to a servlet?

@WebServlet(name = "ServletBlog", urlPatterns = "/posts")
public class Servlets extends HttpServlet {
    {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    }
    catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3300/db","root","root");
             PreparedStatement preparedStatement = null;
             ResultSet resultSet = preparedStatement.executeQuery("SELECT * FROM db")) {

        } catch (SQLException e) {
            System.err.println("DB CONNECT ERROR");
        }


loaded driver in Classpath (in intellij idea(mysql-connector-java-5.1.39-bin.jar)) but still writes "DB CONNECT ERROR"

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
Luka Tarkhnishvili, 2016-06-09
@Zorner

Found the answer:
1.If you're running inside an IDE like Eclipse or IntelliJ, you have to add the JAR to a library.
2.IF you're running in a command shell, use the -p option for javac.exe when you compile and java.exe when you run.
3.If you're using it in a web app, you can start by putting it in the WEB-INF/lib directory of your WAR file. If you're using a servlet/JSP engine like Tomcat 6, put it in the Tomcat /lib directory.
Point 3 worked for me.

Q
qweqwa, 2016-06-09
@qweqwa

You never know. Maybe the password is wrong. Read the logs carefully.

P
protven, 2016-06-09
@protven

Check to see if the jar is in the CP and drag Class.forName into the doCet method before doing getConnection. If it does not help, then xs even.

N
Nikolay Baranenko, 2016-06-10
@drno-reg

And in artifacts, try to create a libs folder, for example, and attach a pre-created libraries instance with mysql drivers

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question