无法使用jdbc连接到数据库

时间:2012-04-25 01:45:31

标签: database jsp servlets login connection

嗨,我对jsp和servlet很新,所以我有一个问题,理解为什么我不能做一个简单的查询。代码用于登录页面,其中用户servlet查询用户发送的数据然后将其与数据库匹配,然后当它找到匹配时返回login == true并执行另一个查询以获得匹配的员工ID号用户名和密码

import java.sql.Connection;
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 javax.sql.*;
import javax.servlet.*;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Driver;
import java.sql.DriverManager;
import javax.servlet.http.HttpSession;


public class Login extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession(); 
            Connection conn = null;
            PreparedStatement prepState = null;
            Statement state = null;
            ResultSet result = null;
            boolean login = false;
            String username = request.getParameter("username");
            String password = request.getParameter("password");                 
            String checkLogin = ("SELECT * FROM users WHERE username = ? AND password = ?");    

            try{

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/matrix","","");

            prepState = conn.prepareStatement(checkLogin);     
            prepState.setString(1, username);
            prepState.setString(2, password);

            result = prepState.executeQuery();

            login = result.next();

            if(login){
                out.println("login");
                String id = result.getString(1);
                String getUser = ("SELECT empLastName, empFirstName FROM employees WHERE empID = ? ");
                prepState = conn.prepareStatement(getUser);
                prepState.setString(1, id);
                result = prepState.executeQuery();
                String first = result.getString(2);
                String last = result.getString(1);

                                    out.println("<html>");
                                    out.println(first + " " + last);
                                    out.println("</html>");
            }


            }catch(Exception e){      
                out.println("ERROR");
                  e.printStackTrace(System.err);
            }   
        }catch(Exception db){


        } finally {            
            out.close();
        }
    }

这是我得到的错误

INFO: The start() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Matrix]] after start() had already been called. The second call will be ignored.
    java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:919)
        at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4004)
        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1284)
        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2312)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2122)
        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:774)
        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:375)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:289)
        at java.sql.DriverManager.getConnection(DriverManager.java:582)
        at java.sql.DriverManager.getConnection(DriverManager.java:185)
        at Login.processRequest(Login.java:57)
        at Login.doPost(Login.java:119)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)

2 个答案:

答案 0 :(得分:2)

这个课在很多方面都是错误的:

  1. 空挡块。你永远不会知道出现了什么问题。
  2. 在servlet中打开连接,而不是使用连接池。
  3. 硬连线驱动程序类和连接URL。
  4. 没有用于连接数据库的凭据。
  5. 一个班级做一切。每班最好有一个责任。
  6. Mingling UI(HTML生成)和数据库访问。
  7. 您不会关闭结果集,对帐单或连接。
  8. 尝试嵌套在另一个尝试;我只推荐一个。
  9. 我现在累了。

    我不清楚问题是什么。你收到错误了吗?如果是,你可以发布堆栈跟踪吗?如果没有,你观察到了什么行为?

答案 1 :(得分:0)

尝试检查您的MySQL用户名和密码。 MySQL有默认用户名“root”

尝试将您的代码更改为此

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/matrix","root","");

这意味着你连接到localhost(同一台计算机)的MySQL服务器,用户名为“root”,密码为空字符串“”(这是默认值)