在 try catch 块中执行 SQL 查询时出现 java.lang.NullPointerException 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19070860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.NullPointerException error while executing SQL query inside try catch block
提问by prince2369
I get java.lang.NullPointerException
error while running the program. Seems like the error appears to be inside the try block:
rs = st.executeQuery(query);
of the method regcustomers
in the below Java code. Please review my code and help me understand what I have done wrong.
我得到java.lang.NullPointerException
运行程序时的错误。似乎错误似乎在 try 块内:
以下 Java 代码rs = st.executeQuery(query);
中的方法regcustomers
。请检查我的代码并帮助我了解我做错了什么。
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vastika.serlvet.dao.ConnectionDb;
public class RegistrationServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Read the data
String name = req.getParameter("name");
String email = req.getParameter("email");
String line1 = req.getParameter("addressline1");
String city = req.getParameter("city");
String state = req.getParameter("state");
String country = req.getParameter("country");
String userid = req.getParameter("username");
String password = req.getParameter("password");
insertToDatabase(name, email, line1, city, state, country, userid,
password);
// Forward to Shopping page
req.getRequestDispatcher("shop.html").forward(req, res);
}
private void insertToDatabase(String name, String email, String line1,
String city, String state, String country, String userid,
String password) {
ConnectionDb con = new ConnectionDb();
Statement st = con.makeConnection();
ResultSet rs = null;
String query = "insert into regcustomers (Name, Email, Address, City, State, Country, Username, Password) values("+"'"+name+"'"+","+"'"+email+"'"+","+"'"+line1+"'"+","+"'"+city+"'"+","+"'"+state+"'"+","+"'"+country+"'"+","+"'"+userid+"'"+","+"'"+password+"'"+");";
System.out.println(query);
try {
rs = st.executeQuery(query);
System.out.println(rs.getRow());
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
and
和
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ConnectionDb {
public Statement makeConnection() {
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlineshopping", "root",
"test");
st = conn.createStatement();
} catch (Exception e) {
e.getStackTrace();
}
return st;
}
}
回答by KhAn SaAb
need not to put semicolon ;
不需要放分号 ;
String query = "insert into regcustomers (Name, Email, Address, City, State, Country, Username, Password) values("+"'"+name+"'"+","+"'"+email+"'"+","+"'"+line1+"'"+","+"'"+city+"'"+","+"'"+state+"'"+","+"'"+country+"'"+","+"'"+userid+"'"+","+"'"+password+"'"+")";
it ll return ResultSet
when you ll hit SELECT
query
ResultSet
当你点击SELECT
查询时它会返回
remove that ResultSet
declaration..
删除那个ResultSet
声明..
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASENAME", "root", "");
Statement st = con.createStatement();
use int count = st.executeUpdate();
用 int count = st.executeUpdate();
回答by Cold
U can try do this:
你可以尝试这样做:
private void insertToDatabase(String name, String email, String line1,
String city, String state, String country, String userid,
String password) {
ConnectionDb con = new ConnectionDb();
Statement st = con.makeConnection();
ResultSet rs = null;
String query = "insert into regcustomers (Name, Email, Address, City, State, Country, Username, Password) values(?,?,?,?,?,?,?,?)";
st.setString(1,name);
st.setString(2,email);
st.setString(3,line1);
st.setString(4,street);
st.setString(5,state);
st.setString(6,country);
st.setString(7,userid);
st.setString(8,passwoname);
try {
int flag = st.executeUpdate(query);
}
catch (SQLException e) {
e.printStackTrace();
}
}
I think what u wannna do is not a query, is more an update. So intead of:
我认为你想要做的不是查询,而是更新。因此,而不是:
rs = st.executeQuery(query);
U can do something like:
你可以做这样的事情:
int flag = st.executeUpdate(query);
See thisto have more info.
看到这个有更多的信息。
Att: u are having a NullPointer Exception because(maybe) rs = st.executeQuery(query);
retrieve nothing.
Att:你有一个 NullPointer 异常,因为(也许)rs = st.executeQuery(query);
什么都没有检索到。
Hope it helps ^^
希望有帮助^^
回答by Sotirios Delimanolis
What's happenning is that you are getting an exception in the following code
发生的事情是您在以下代码中遇到异常
public Statement makeConnection() {
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlineshopping", "root",
"test");
st = conn.createStatement();
} catch (Exception e) {
e.getStackTrace();
}
return st;
}
and then return st
which is null
because the code never got to conn.createStatement()
.
然后返回st
,这是null
因为代码从未到达conn.createStatement()
。
You're not actually printing the Exception
by the way. Use e.printStackTrace()
.
Exception
顺便说一下,您实际上并没有打印。使用e.printStackTrace()
.
Also you should actually handle the exception.
此外,您应该实际处理异常。
回答by Dan Hagiiani
There is a strange situation when java.lang.NullPointerException error is triggered while executing SQL query inside try catch block. The query updates selected index in several JComboboxes. These JComboboxes are initially linked to update manually indexes according to a shema:
在 try catch 块中执行 SQL 查询时触发了 java.lang.NullPointerException 错误,这是一个奇怪的情况。查询更新多个 JComboboxes 中的选定索引。这些 JComboboxes 最初链接到根据 shema 手动更新索引:
private void PriorityLoad6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
NewSelectedIndex = PriorityLoad6.getSelectedIndex(); SetNewIndexes();
}
In this situation, when performing mysql update with a simple
在这种情况下,当使用简单的方式执行 mysql 更新时
PriorityLoad6.setSelectedIndex(rs.getInt("PriorityLoad_6"));
the above mentioned error is triggered. In this situation one solution is to "isolate" the code inside with an if which is not active during query. For example:
触发了上述错误。在这种情况下,一种解决方案是使用在查询期间不活动的 if 来“隔离”内部代码。例如:
private void PriorityLoad6ActionPerformed(java.awt.event.ActionEvent evt) {
if (SaveSettings.hasFocus() == false){NewSelectedIndex = PriorityLoad6.getSelectedIndex(); SetNewIndexes();}}
This action should be of course preceded by adequately placed:
当然,此操作之前应适当放置:
SaveSettings.requestFocus();
before calling the mysql query.
在调用 mysql 查询之前。