[英]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 从定义了main()
类的Java文件创建与SQL的连接效果很好,但是在Java Servlet中的doPost()
内部调用该方法会抛出Error,
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 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 在上面的代码中, new DbQuery().isValidLogin(userName, password)
创建一个数据库连接,而该Class用作
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
On hitting the above line ........ ERROR 在碰到上述行........错误
please help. 请帮忙。
You need to put sqljdbc jar in your application server. 您需要将sqljdbc jar放入应用服务器中。 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. 例如,如果您使用的是tomcat服务器,请转到已安装tomcat的目录,打开LIB目录,并确保在那里存在sqljdbc jar。
I got the same error while deploying the similar application in Tomcat Server. 在Tomcat服务器中部署类似应用程序时遇到了相同的错误。 Put the relevant jdbc jar in the lib folder of Tomcat. 将相关的jdbc jar放在Tomcat的lib文件夹中。 It should work fine. 它应该工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.