(抱歉我有大量代码,但我真的不知道多少才足够)
我在将值插入 mysql 数据库时遇到问题。我使用 Jsp 文件而不是 html 文件。我不断收到此错误,但不确定是什么原因造成的。
public class AddTo extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
{
String name = request.getParameter("name");
String dbURL = "jdbc:mysql://localhost:3306/movieDB";
String username = "root";
String password = "sund ";
try {
Connection conn = (Connection) DriverManager.getConnection(
dbURL, username, password);
}
catch (SQLException ex) {
Logger.getLogger(AddTo.class.getName()).log(Level.SEVERE, null, ex);
}
String query = "INSERT INTO table1 " + "VALUES ('" + name + "')";
Statement statement = null;
statement = (Statement) conn.createStatement();
statement.executeUpdate(query);
Movie aMovie = new Movie(request.getParameter("name"));
request.setAttribute("user", aMovie);
String cartRadio = request.getParameter("cartRadio");
if ( cartRadio.equalsIgnoreCase("cartSelect") ) {
String url = "/jsp2.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
if ( cartRadio.equalsIgnoreCase("listSelect")) {
String url = "/jsp3.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
if ( cartRadio.equalsIgnoreCase("none")) {
String url = "/jsp4.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(AddTo.class.getName()).log(Level.SEVERE, null, ex);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(AddTo.class.getName()).log(Level.SEVERE, null, ex);
}
}
private Object getServletContext() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
我不断收到的一个错误是“不兼容的类型要求:com.mysql.jdbc.Statement 发现:java.sql.Statement”,其中“statement = conn.createStatement();”是。
最佳答案
看来您有导入声明
import com.mysql.jdbc.Statement;
而不是
import java.sql.Statement;
这已在本网站上多次说明,但您应该考虑使用 PreparedStatement
相反,为了防止 SQL Injection attacks .
关于java - 如何使用 Java servlet 将值插入到 mysql 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424884/