如何在servlet中声明的变量值用于新的Java类中?

时间:2018-11-15 05:18:46

标签: java

我有一个登录servlet,在该方法中,我从查询中获取用户名密码公司名称 ID

我将所有这些值存储在一个变量中,例如

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    String companyDB,nameDB,idDB;

        try {
                    con = DBConnection.createConnection();
                    statement = con.createStatement();
                    String sql = "  SELECT MT_USERS.MT_USERS_VCLOGINCODE AS USERID, MT_USERS.MT_USERS_VCUSERPASSWORD AS PASSWORDID, MT_USERS.MT_USERS_VCUSERNAME AS NAME, (SELECT MT_DISTRIBUTR_VCDISTRIBUTRNAME FROM MT_DISTRIBUTR WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS COMPANYNAME ,(SELECT mt_distributr_vcdistributrcode FROM mt_distributr WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS ID FROM MT_USERS WHERE MT_USERS_VCLOGINCODE='admin' AND MT_USERS_VCUSERPASSWORD ='admin'";
                    resultSet = statement.executeQuery(sql);
                    if (resultSet.next()) {

                        companyDB = resultSet.getString("COMPANYNAME");
                        nameDB = resultSet.getString("name");
                        idDB = resultset.getString("ID");  


                    }

                } catch (SQLException e) {
                    e.printStackTrace();

}
}

现在我有另一个班级正在编写查询,在该查询中我想使用 idDB 之类的

我的新课是

 public class Outlet {
    Connection con = null;
    Statement statement = null;
    ResultSet resultSet = null;

    public List<String> getoutlet() throws ClassNotFoundException, SQLException {
        List<String> list = new ArrayList<String>();
        con = DBConnection.createConnection();
        statement = con.createStatement();

        try {

            ResultSet resultSet = statement.executeQuery("select * from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = 'AAAA'");
            while (resultSet.next()) {
                list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

}

在mt_distributr_vcdistributrcode ='AAAA'“的位置,我必须传递一个值为 idDB

的变量

1 个答案:

答案 0 :(得分:2)

您可以在此处使用准备好的语句:

String sql = "SELECT CUSTOMERDESCRIPTOR FROM ecustomer WHERE CUSTOMERIDENTIFIER IN (";
sql += "SELECT CUSTOMERIDENTIFIER FROM mt_distributrol ";
sql += "WHERE mt_distributr_vcdistributrcode = ?)");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "AAAA");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}

我实际上发现MkYong在用Java see here解释准备好的语句方面做得很好,但是任何好的文档都是开始查找的好地方。并查看Oracle Tutorial