Answer the question
In order to leave comments, you need to log in
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");
}
Answer the question
In order to leave comments, you need to log in
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.
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.
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 questionAsk a Question
731 491 924 answers to any question