为什么 DataSource 不能与 JSP 中的 PreparedStatement 一起使用?

Why DataSource not work with PreparedStatement in JSP?

我实现了与createstatement 的连接DataSource,但是PreparedStatement 有问题。错误:java.lang.NullPointerException

<%@page import="java.sql.*, javax.sql.*, javax.naming.*,java.sql.PreparedStatement;"%>

DataSource ds;
Connection con= null;
PreparedStatement ps = null;
ResultSet rs = null;


String sql = "select * from test where...";

String name= request.getParameter("name");


if((!(name.equals(null))
{
try{
Context context = new InitialContext();
ds =  (DataSource)context.lookup("jdbc/DataSourceConn");
ps = con.prepareStatement(sql);
ps.setString(1, name);

rs = ps.executeQuery();
if(rs.next())
{ 
userdbName = rs.getString("name");
...

您需要添加以下代码才能实际生成 connection 而不是 null:

con = ds.getConnection();

像这样

Context context = new InitialContext();
ds =  (DataSource)context.lookup("jdbc/DataSourceConn");
con = ds.getConnection();
ps = con.prepareStatement(sql);
ps.setString(1, name);