我试图在doPost()
方法中在这个servlet中建立与数据库(MySQL)的连接。我不知道问题出在哪里。我可以在这个servlet中建立连接,还是需要创建一个新的Java类?
package com.EventListing.servlets;
import java.io.IOException;
import java.sql.Connection;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ViewEventListing extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String eventTitle= request.getParameter("eventTitle");
String location = request.getParameter("location");
out.println("Welcome "+ eventTitle+"! The Email Address "+location+" has been "
+ "added to our mailing list.");
try {
Class.forName("com.mysql.jdbc.Driver");
out.println("Driver Loading Done!");
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
String connURL = "jdbc:mysql://localhost/eventlistings" ;
String user = "root";
String pass = "sheridan";
Connection conn ;;
try {
conn = DriverManager.getConnection(connURL, user, pass);
} catch (SQLException ex) {
Logger.getLogger(ViewEventListing.class.getName()).log(Level.SEVERE, null, ex);
}
out.println("Connection Done!");
String sql = "INSERT INTO eventlistings "+"(Title, Location)" +
"VALUES('simran', 'Brampton');";
PreparedStatement ps = conn.prepareStatement();
out.close();
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
这是我想要从MySQL获取一些数据的servlet,但我甚至无法连接到数据库。我试图使用Prepared语句,即preparedStatement ps,我得到一个错误。
代替:
PreparedStatement ps = conn.prepareStatement();