在Java Web应用程序中通过NetBeans将JDBC转换为MySQL

问题描述 投票:0回答:1

我试图在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,我得到一个错误。

java mysql jsp servlets
1个回答
1
投票
  1. 只使用Prepared语句,您希望在其中重用具有不同参数的sql
  2. 建议你改用 语句stmt = conn.createStatement(); stmt.execute(SQL);

代替:

PreparedStatement ps = conn.prepareStatement();
© www.soinside.com 2019 - 2024. All rights reserved.