空指针异常。我的连接对象为什么指向空值。

huangapple go评论67阅读模式
英文:

Null pointer exception. How my connection object is pointing to null

问题

The stacktrace

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
	at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1952)
	...

Sep 01, 2020 9:06:08 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegisterServlet] in context with path [/Registration] threw exception
java.lang.NullPointerException
	at Store.insertuser(Store.java:31)
	...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Store {
	Connection connection;

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

			String username = "sa";
			String password = "123456abcd";
			String url = "jdbc:sqlserver://localhost;databaseName=Register";

			connection = DriverManager.getConnection(url, username, password);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public boolean insertuser(String string1, String string2, String string3, String string4, String string5) throws SQLException{
		
		String sql = "insert into dbo.Usertable values(?,?,?,?,?)";
		
		PreparedStatement pstmt = connection.prepareStatement(sql);

		pstmt.setString(1, string1);
		pstmt.setString(2, string2);
		pstmt.setString(3, string3);
		pstmt.setString(4, string4);
		pstmt.setString(5, string5);
		int i = pstmt.executeUpdate();
		if (i > 0) {
			return true;
		}
		
		return false;
	}
}

I have a class named Store. I establish a JDBC connection in the constructor Store(). I attempt to insert values into the Usertable using the method insertuser. However, I encounter a NullPointerException at line 31 of the Store class, which is within the insertuser method.

It seems that the initial issue originates from a missing class: com.microsoft.sqlserver.jdbc.SQLServerDriver. This class is not found, resulting in the ClassNotFoundException in the stacktrace.

Make sure you have the necessary JDBC driver JAR file for SQL Server in your classpath. Additionally, ensure that the driver class name and the connection URL are correctly specified. Once the driver issue is resolved, the connection object should be initialized properly and the NullPointerException should be resolved as well.

英文:

The stacktrace

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
	at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1952)
	at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1795)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at Store.<init>(Store.java:12)
	at RegisterServlet.doGet(RegisterServlet.java:38)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
Sep 01, 2020 9:06:08 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [RegisterServlet] in context with path [/Registration] threw exception
java.lang.NullPointerException
	at Store.insertuser(Store.java:31)
	at RegisterServlet.doGet(RegisterServlet.java:40)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1201)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class Store {
	Connection connection;

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

			String username = "sa";
			String password = "123456abcd";
			String url = "jdbc:sqlserver://localhost;databaseName=Register";



			connection = DriverManager.getConnection(url, username, password);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public boolean insertuser(String string1, String string2, String string3, String string4, String string5) throws SQLException{
		
		String sql = "insert into dbo.Usertable values(?,?,?,?,?)";
		
		PreparedStatement pstmt = connection.prepareStatement(sql);//this is the place where connection is null

		pstmt.setString(1, string1);
		pstmt.setString(2, string2);
		pstmt.setString(3, string3);
		pstmt.setString(4, string4);
		pstmt.setString(5, string5);
		int i = pstmt.executeUpdate();
		if (i > 0) {
			return true;
		}
		
		return false;
	
	
		
	}

	

}



i have a class store. I connect jdbc in init. I insert values in usertable in a method insertuser. My connection object is pointing to null. My usertable has five varchar values in a database called Register. Why my connection object is pointing to null.I have jdbc jar connected to my classpath.

答案1

得分: 3

如果Store构造函数遇到任何异常,它将打印堆栈跟踪信息,并返回一个部分构造的Store对象,其中在connection字段中为null

这可以解释您所看到的情况。但是,如果没有看到(完整的)堆栈跟踪信息,我们无法告诉您捕获异常的原因。这种情况的典型解释包括:

  • 数据库驱动程序JAR不在类路径中(正确地)
  • 不正确的数据库驱动程序JAR
  • 不正确的数据库凭据
  • 不正确的数据库主机或端口信息
  • 网络问题

您可以修复的问题:

  • 正如评论者指出的,您构造函数中的异常处理有问题。如果在设置连接时出现异常,构造函数应该以异常终止。调用者需要处理它,或允许其传播。
  • 如果您使用DriverManager.getConnection,则不需要使用Class.forName来加载JDBC驱动程序。DriverManager基础设施将根据jdbc URL自行查找驱动程序。
英文:

If the Store constructor encounters any exception, it will print a stacktrace and return a partially constructed Store object with a null in the connection field.

That would explain what you are seeing. But we can't tell you the cause of the exception you are catching without seeing the (complete) stacktrace. Typical explanations for this kind of thing include:

  • Database driver JAR not the classpath (correctly)
  • Incorrect database driver JAR
  • Incorrect database credentials
  • Incorrect database host or port information
  • Network problems

Things you could fix:

  • As commenters pointed out, the exception handling in your constructor is broken. If you get an exception while setting up the connection, the constructor should terminate with an exception. The caller needs to deal with it, or allow it to propagate.
  • If you use DriverManager.getConnection you shouldn't need to use Class.forName to load the JDBC driver. The DriverManager infrastructure will find the driver for itself, based on what the jdbc URL says.

答案2

得分: 0

你需要将包含类com.microsoft.sqlserver.jdbc.SQLServerDriver的jar文件添加到你的war文件的WEB-INF/lib文件夹中。

英文:

You need to add the jar file containing the class com.microsoft.sqlserver.jdbc.SQLServerDriver to your war file's WEB-INF/lib folder.

huangapple
  • 本文由 发表于 2020年9月1日 23:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63690893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定