简体   繁体   English

无法在NetBeans Java Web应用程序中连接到mysql数据库

[英]Unable to get connection to mysql database in netbeans java web application

I am new to web development to java. 我是Java Web开发的新手。 I am writing this basic java web application that is going to store customer information into a database. 我正在写这个基本的Java Web应用程序,它将客户信息存储到数据库中。 I use the MVC-2 architecture. 我使用MVC-2架构。 My Jsp sends a request to a servlet that in turn tries instatiates a bean an inserts that object into a database. 我的Jsp向Servlet发送一个请求,该Servlet进而尝试使Bean实例化并将该对象插入数据库。 When i try to connect to the database (in debugging mode) the connection variable returns empty. 当我尝试连接到数据库(在调试模式下)时,连接变量返回空。 So data cannot be inserted. 因此无法插入数据。

This is the class that makes connections to the db 这是建立与数据库连接的类

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package customer;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author 
 */
public class DatabaseOperations implements Serializable 
{
    private static Connection connection;
    public DatabaseOperations()
    {
        try
        {
            String username = "root";
            String password = "root";
            String url = "jdbc:mysql://localhost/test";
            Class.forName ("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection (url, username, password);

            System.out.println("Database connection established");
        }
        catch(Exception e)
        {

        }
    }

    public static Connection getConnection()
    {
        return connection;
    }
}

This is the method that adds a customer to the db 这是将客户添加到数据库的方法

public void addCustomer(CustomerBean customer) throws SQLException {
        DatabaseOperations db = new DatabaseOperations();
        connection = DatabaseOperations.getConnection();
        statement = connection.createStatement();

        String query = "insert into customer (name, address, phone, email) "
                + "values (" + customer.name + ","
                + customer.address + ","
                + customer.phone + ","
                + customer.email + "," + ")";

        statement.executeUpdate(query);
    }

and finally this is the servlet where i call the method to add a customer 最后是servlet,我在其中调用添加客户的方法

   /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package customer;

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import customer.CustomerBean;
    import javax.servlet.RequestDispatcher;

    /**
     *
     * @author 
     */
    public class CustomerServlet extends HttpServlet {

        /**
         * Processes requests for both HTTP
         * <code>GET</code> and
         * <code>POST</code> methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();

            CustomerBean customer = new CustomerBean();
            try {
                out.println("tests");

                customer.setName(request.getParameter("name"));
                customer.setEmail(request.getParameter("email"));
                customer.setAddress(request.getParameter("address"));
                customer.setPhone(request.getParameter("phone"));

/************** ADD CUSTOMER TO DB HERE***********************/
                customer.addCustomer(customer);

                request.setAttribute("cust", customer);
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            } 
            catch (Exception e) 
            {            
                e.printStackTrace();

            }
        }

First, I'd like to point out that your code is open to SQL injection. 首先,我想指出您的代码可以进行SQL注入。 Personally, I'm a fan of procedures, so I'll recommend that: you should create a procedure in mysql to insert a new record, and then provide that sproc with the arguments (name, address, etc). 就个人而言,我是过程的狂热者,因此我建议:您应该在mysql中创建一个过程以插入新记录,然后为该proc提供参数(名称,地址等)。

As for the problem at hand: After your statement.executeUpdate line, try closing the connection. 至于眼前的问题:在statement.executeUpdate行之后,尝试关闭连接。 Also, extract the Class.forName to your main method. 另外,将Class.forName提取到您的main方法中。 It should only be executed once. 它只能执行一次。 Also, remove the .newInstance() off of that once you have done so. 此外,一旦删除.newInstance()即可。

If all that doesn't work, extract the entire connection out to a globally accessible static variable and do not assign to it more than once . 如果所有方法都不起作用,请将整个连接提取到全局可访问的静态变量中, 并且不要多次分配给它 See if your program works then. 看看程序是否可以正常工作。 If not, you have a separate problem. 如果没有,您将遇到另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM