不能将PreparedStatement与DataSource类型连接一起使用

时间:2014-12-18 20:27:11

标签: mysql servlets prepared-statement sqldatasource

当我在表中插入值时使用DataSource类型连接时,我似乎并没有让PreparedStatement工作。 我尝试了类型转换:

PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement("Some query");

但这似乎也不起作用并抛出空指针异常!

(P.S:我知道我可以达到同样的目标

  

Statement stmt = conn.createStatement(); String sql =“INSERT INTO ... VALUES   (.....)“; stmt.executeUpdate(sql);

但我不想这样做!)

这是我的代码。 (所有.jar都已到位且引用的表和列名称有效且存在):

        import java.sql.*;
        import javax.sql.DataSource;
        import com.mysql.jdbc.PreparedStatement;
        //...and all other necessary imports

        public class CreateUserAccountDaoImpl implements CreateUserAccountDaoInterface {

            @Override
            public boolean validate(CreateUserAccountBean cuab) {


            int resstat=0;
            java.io.PrintWriter out = null;
            Connection conn=null;
    //CallableStatement cStmt=null;


    try {
        /* get the DataSource from using the JNDI name */
        Class.forName("com.mysql.jdbc.Driver");
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Test");
        //username, pass,name, id,dob ,skillset, exp,designation ,email
        //Create connection and then continue as usual other JDBC calls 
        conn=ds.getConnection();
        //System.out.println("\nConnection Successful in " +lb.getBeanclassname()+ " !");

        String sql = "INSERT INTO tbluser (username,pass,category,dname,id,dob,skillset,exp,designation,email)"
                + " VALUES (?, ?, ? ,?, ?, ? , ?, ?, ?, ?)";
        //Create a PreparedStatment with that sql and insert the values with index:
        /*1-username 2-pass 3-category 4-dname
        5-id 6-dob 7-skillset 8-exp 9-designation 14-email*/
        PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(sql);
        preparedStatement.setString(1,cuab.getBeannuusrname());
        preparedStatement.setString(2,cuab.getBeannupass());
        preparedStatement.setString(3,cuab.getBeanusertype());
        preparedStatement.setString(4,cuab.getBeannuname());
        preparedStatement.setString(5,cuab.getBeannuempid());
        preparedStatement.setString(6,cuab.getBeannudob());
        preparedStatement.setString(7,cuab.getBeannuskill());
        preparedStatement.setString(8,cuab.getBeannuexp());
        preparedStatement.setString(9,cuab.getBeannudesg());
        preparedStatement.setString(10,cuab.getBeannuemail());
        preparedStatement.executeUpdate(); 
        preparedStatement.clearParameters();
        resstat=1;
        System.out.println("Data inserted successfully!");

    } catch (Exception e){

        out.println("Failed!"+ e);
        resstat=0;
    }

    if(resstat==1)
        return true;
    else
        return false;

    }

}

0 个答案:

没有答案