我目前正在servlet中创建一个私有方法。但我的PreparedStatement
不断返回null
。
private ArrayList<String> emails(String id) {
ArrayList<String> email= new ArrayList<String>();
try {
PreparedStatement st = null;
ResultSet data = null;
DriverManager.getConnection(
"jdbc:postgresql://localhost/test",
"test", "test");
String sql = "SELECT email FROM hdpr.email_table WHERE id='"
+ id+ "'";
data = st.executeQuery(sql);
while (data.next()) {
email.add(data.getString("email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
e.getMessage();
}
return email;
}
答案 0 :(得分:3)
private ArrayList<String> emails(String id) {
ArrayList<String> email= new ArrayList<String>();
try {
PreparedStatement st = null;
ResultSet data = null;
// Creating a new connection
Connection con = DriverManager.getConnection(
"jdbc:postgresql://localhost/test",
"test", "test");
// your SQL Query now with a ? as parameter placeholder
String sql = "SELECT email FROM hdpr.email_table WHERE id = ?";
// creating a new preparedStatement using your sql query
st = con.prepareStatement(sql);
// set the first ? to the value of id
st.setString(1, id);
data = st.executeQuery();
while (data.next()) {
email.add(data.getString("email"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
return email;
}
如果您将null
分配给变量,则null
如果您尝试从该对象调用方法,则NullpointerException
将始终发生。
要使用PreparedStatement st
,您需要使用连接和SQL查询创建preparedStatement来初始化它。
不要使用+
运算符向SQL查询添加参数 - 这将为 SQL注入打开大门,为此我们准备好了语句并{{1} },setString()
,...
你应该看看教程,比如说:http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/