Asit Tripathy
Asit Tripathy

Reputation: 133

Create a connection to SQL Server DB inside Servlet request Thows "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver"

Create a connection to SQL from a Java file with main() class defined works fine but calling the method inside a doPost() in Java Servlet throwing Error as

java.lang.ClassNotFoundException:com.microsoft.sqlserver.jdbc.SQLServerDriver

Working Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Connect{

    public static void main(String[] args) throws Exception
      {

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String url = "jdbc:sqlserver://localhost;databaseName=UserDB";
        Connection con = DriverManager.getConnection(url,"sa","XXXXXXX");

        String query =" SELECT * FROM Login";


        Statement myStatement = null;
        myStatement = con.createStatement();
        ResultSet result = myStatement.executeQuery(query);

        while(result.next()){
            System.out.println("User name = " + result.getString("userID"));
            System.out.println("User password = " + result.getString("userPassword"));
        }

      }
}

Now Working Code inside Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName= request.getParameter("username");
        String password= request.getParameter("password");

        try {
            if( **new DbQuery().isValidLogin(userName, password)**)
            {
                response.getWriter().println("Welcome " +userName);
            }

            else{
                response.getWriter().println("Please Enter a valid User name and Password");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

In the above code new DbQuery().isValidLogin(userName, password) creates a DB connection and the Class used as

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

On hitting the above line ........ ERROR

please help.

Upvotes: 1

Views: 4892

Answers (2)

Goyal Vicky
Goyal Vicky

Reputation: 1299

I got the same error while deploying the similar application in Tomcat Server. Put the relevant jdbc jar in the lib folder of Tomcat. It should work fine.

Upvotes: 1

Vishal
Vishal

Reputation: 804

You need to put sqljdbc jar in your application server. For example if you are using tomcat server, go to the directory where you have installed the tomcat, open the LIB directory and make sure you have sqljdbc jar exists over there.

Upvotes: 4

Related Questions