已连接到数据库但无法执行操作

时间:2016-12-08 15:16:49

标签: java sql-server database servlets jdbc

我正在尝试从我的应用程序访问SQL Server数据库。从我的连接工厂类成功连接,但由于某种原因,我为登录触发的JDBC查询无法获取任何详细信息。 SQL Server安装在本地计算机中,并且存在所有用户和数据库。所有依赖库已成功导入并放置在WEB-INF / lib文件夹中,以供Web应用程序访问。 (基本上没有外部依赖项。)我已经使用SQL Server Management Studio测试了我在前端的Login servlet中使用的查询,它正确地获取了详细信息。我无法理解查询无法正常工作的地方。

以下是连接工厂类的代码。

package com.util;
import java.sql.*;

public class ConnectionFactory {

    static String url="jdbc:sqlserver://localhost:1433;DatabaseName=Portal";
    static String uname="Portal";
    static String pass="portal_1";
    static String driverclass="com.microsoft.sqlserver.jdbc.SQLServerDriver";

    private ConnectionFactory(){

    }

    public static Connection getConn() throws ClassNotFoundException, SQLException{
        Class.forName(driverclass);
        Connection connection = DriverManager.getConnection(url, uname, pass);
        return connection;
    }
}

我正在使用此类在需要连接数据库的地方创建并返回连接对象。

以下是登录模块,它是我用来在输入凭据后用户在索引页面中单击登录时执行登录操作的servlet。

import com.util.CommonOps;
import com.util.ConnectionFactory;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public Login() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    HttpSession sess = request.getSession();

    String uname = (String) request.getParameter("uname");
    String pass = (String) request.getParameter("pass");

    // System.out.println(pass);
    uname = CommonOps.sanitzeData(uname);
    pass = CommonOps.sanitzeData(pass);

    // System.out.println(pass);

    // Username can be in any case.can It will take the upper case value by
    // default.

    uname = uname.toUpperCase();
    uname = uname.trim();

    if (uname == null) {
        response.sendRedirect("index.jsp");
        sess.setAttribute("msg", "Invalid Username or Password");
    } else if (pass == null) {
        sess.setAttribute("msg", "Invalid Username or Password");
        response.sendRedirect("index.jsp");
    } else {
        String pass_hash = CommonOps.getHash(pass);

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // System.out.println("Inside Try block");
            conn = ConnectionFactory.getConn();
            if(conn == null){
                System.out.println("Connection Failed");
            }
            else{
                System.out.println("Connection Successful");
            }
            System.out.println(conn);
            try {
                stmt = conn.createStatement();
                try {

                    System.out.println(uname);
                    System.out.println(pass_hash);

                    sql = "select lg_uname, lg_pwd, lg_u_role from login where lg_uname='"
                                    + uname
                                    + "' and lg_pwd='"
                                    + pass_hash
                                    + "' "
                                    + "and lg_del_flg='N'"
                                    + "and lg_entity_cre_flg='Y'";

                    System.out.println(sql);

                    rs = stmt.executeQuery(sql);

                    if (rs.next()) {

                        sess.setAttribute("uname", uname);
                        String role = rs.getString(3);
                        sess.setAttribute("role", role);

                        response.sendRedirect("redirect_home.jsp");

                    } else {
                        // System.out.println("Outside while block");
                        sess.setAttribute("msg",
                                "Invalid Username or Password");
                        response.sendRedirect("index.jsp");
                    }
                } catch (SQLSyntaxErrorException sql) {
                    sess.setAttribute("msg", "Invalid Username or Password");
                    response.sendRedirect("index.jsp");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (rs != null)
                        rs.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("Error when closing result set");
            } finally {
                if (stmt != null)
                    stmt.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error when closing statement");
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("Error when closing connection");
                }
        }

    }
}
}

我已经插入了一些print语句,以便检查是否正在建立连接,以及是否将有效数据传递给servlet并按顺序传递给数据库。

以下是我点击登录按钮时收到的错误的堆栈跟踪。

Dec 8, 2016 11:51:52 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:/Program Files/Java/jre6/lib/i386;E:\app\IAS_Admin\product\11.2.0\client_1;E:\app\IAS_Admin\product\11.2.0\client_1\bin;E:\oracle\oraclient\bin;C:\Program Files\Oracle\jre\1.1.7\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;E:\oracle\oraclient\orb\bin;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\StaffPortalWork\Software\eclipse-jee-indigo-SR2-win32\eclipse;;.
Dec 8, 2016 11:51:52 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:StaffPortalMasterTemplate' did not find a matching property.
Dec 8, 2016 11:51:52 AM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8020
Dec 8, 2016 11:51:52 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 375 ms
Dec 8, 2016 11:51:52 AM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Dec 8, 2016 11:51:52 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.41
Dec 8, 2016 11:51:52 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8020
Dec 8, 2016 11:51:52 AM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Dec 8, 2016 11:51:52 AM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/16  config=null
Dec 8, 2016 11:51:52 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 332 ms
Inside Try block
Connection successful
ConnectionID:1 ClientConnectionId: 2ce17bbd-c66d-4461-9276-e23302f4d8ba
ADMIN1
5058f1af8388633f609cadb75a75dc9d
select lg_uname, lg_pwd, lg_u_role from dbo.login where lg_uname='ADMIN1' and lg_pwd='5058f1af8388633f609cadb75a75dc9d' and lg_del_flg='N'and lg_entity_cre_flg='Y'
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:800)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616)
    at com.serv.Login.doPost(Login.java:116)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

我正在使用具有相同目标运行时的JDK 1.6版的Eclipse Indigo IDE。我使用Apache Tomcat版本6作为部署的首选应用程序服务器。有了这个,我使用MSSQL Server 2008的快速版作为数据库。除此之外,操作系统是Microsoft Server 2008.所有都是32位版本。

感谢任何帮助。

编辑09/12/2016(DD / MM / YYYY): 根据要求,这是删除打印堆栈跟踪后的错误语句。它是在我试图关闭try catch块中的语句的部分抛出错误。

Dec 9, 2016 8:27:55 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:/Program Files/Java/jre6/lib/i386;E:\app\IAS_Admin\product\11.2.0\client_1;E:\app\IAS_Admin\product\11.2.0\client_1\bin;E:\oracle\oraclient\bin;C:\Program Files\Oracle\jre\1.1.7\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;E:\oracle\oraclient\orb\bin;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\StaffPortalWork\Software\eclipse-jee-indigo-SR2-win32\eclipse;;.
Dec 9, 2016 8:27:55 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to     'org.eclipse.jst.jee.server:StaffPortalMasterTemplate' did not find a matching property.
Dec 9, 2016 8:27:55 AM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8020
Dec 9, 2016 8:27:55 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 553 ms
Dec 9, 2016 8:27:55 AM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Dec 9, 2016 8:27:55 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.41
Dec 9, 2016 8:27:56 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8020
Dec 9, 2016 8:27:56 AM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Dec 9, 2016 8:27:56 AM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/25  config=null
Dec 9, 2016 8:27:56 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 519 ms
Error when closing statement

1 个答案:

答案 0 :(得分:-1)

在SQL中,您缺少“lg_del_flg ='N'和”的空格,这可能会使您查询失败。其他一切都跟着......