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

时间:2015-10-22 17:09:25

标签: jsp prepared-statement datasource

我意识到连接DataSource与createstatement,但我遇到了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");
...

1 个答案:

答案 0 :(得分:0)

您需要添加以下代码才能真正制作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);