Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7181731
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T17:37:08+00:00 2026-05-28T17:37:08+00:00

the whole data operation is below. i want to close close each and every

  • 0

the whole data operation is below. i want to close close each and every resource without interfering with the next connection. should i change the constructor to a connection() mthod then have a disconnect() mthod, but after doing so where should i

public class DataBean{


    private Connection conn = null;
    private ResultSet res = null;
    private InitialContext context;
    private DataSource datasource;
    private Statement stmt=null;
    private java.sql.PreparedStatement prepar = null;
    private java.sql.CallableStatement proc = null;
    public static int PAGECOUNT; //²éѯºó·µ»ØµÄ×ÜÒ³Êý ÒòΪjavaµÄº¯Êý²»ÄÜ´«ÒýÓÃËùÒÔÐèÒªÓþ²Ì¬±äÁ¿À´»ñµÃ
    public DataBean()
    {
        try {

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/MyData", "root","loikenu");
            context = new InitialContext();
            datasource = (DataSource)context.lookup("jdbc/MyData");
            conn = datasource.getConnection();


            //stmt =conn.createStatement();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }


    public UserBean checkUsersLogin(String userName, String userPwd) //µÇ½ÑéÖ¤
    {
        UserBean ub = null;
        if (!checkParameter(userName + userPwd))
        {
            userName = "null";
            userPwd = "null";
        }
        try
        {
            String sql =
                "select count(*) from admin where userName=? and userPwd=?";

            prepar = conn.prepareStatement(sql);
            //set parameter values for preparedstatment object
            prepar.setString(1, userName);
            prepar.setString(2, userPwd);
            //execute query using preparedstatement object
            res = prepar.executeQuery();
            if (res.next())
            {
                //get data from reults set returned by jdbc
                if (res.getInt(1) > 0)
                {
                    ub = this.getUser(userName);
                }
                else
                {
                    ub = null;
                }
            }
        }
        catch (Exception e)
        {
            ub = null;
            e.printStackTrace();
        }
        return ub;
    }

    public UserBean getUser(String userName) //ÌáÈ¡µÇ½Óû§ÐÅÏ¢
    {
        UserBean ub = new UserBean();
        int i=1;
        String sql = "select * from admin where userName=?";
        try
        {
            prepar = conn.prepareStatement(sql);
            prepar.setString(1, userName);
            res = prepar.executeQuery();
            while (res.next())
            {
                ub.setUserName(res.getString("userName"));
                ub.setUserPwd(res.getString("userPwd"));
                ub.setUserId(i);

            }
            i++;
        }

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

        return ub;
    }

    public boolean checkParameter(String para) //¹ýÂË·Ç·¨×Ö·û
    {
        int flag = 0;
        flag += para.indexOf("'") + 1;
        flag += para.indexOf(";") + 1;
        flag += para.indexOf("1=1") + 1;
        flag += para.indexOf("|") + 1;
        flag += para.indexOf("<") + 1;
        flag += para.indexOf(">") + 1;
        if (flag != 0)
        {
            System.out.println("Ìá½»ÁË·Ç·¨×Ö·û!!!");
            return false;
        }
        return true;
    }

    public ArrayList selectCDBean(String selectValue, int page, int count) //²éѯ·ÖÒ³
    {
        ArrayList list = new ArrayList();
        if (!checkParameter(selectValue))
        {
            selectValue = "";
        }
        try
        {
            proc = conn.prepareCall("{call proc_page(?,?,?,?)}");
            proc.setInt(1, page);
            proc.setInt(2, count);
            proc.setString(3, selectValue);
            proc.registerOutParameter(4, Types.INTEGER); //OUTPUT²ÎÊý ·µ»Ø½á¹¹¹²¶àÉÙÒ³
            res = proc.executeQuery(); //½ÓÊÕ´æ´¢¹ý³ÌµÄ½á¹û¼¯
            while (res.next()) //ÌáÈ¡½á¹û¼¯µÄÿÌõ¼Ç¼
            {
                CDBean cb = new CDBean();
                cb.setCdAlbum(res.getString("CDalbum"));
                cb.setCdCompany(res.getString("CDcompany"));
                cb.setCdName(res.getString("CDname"));
                cb.setCdId(res.getLong("CDid"));
                cb.setCdType(getCDType(res.getInt("CDtypeId")));
                list.add(cb);
            }
            PAGECOUNT = proc.getInt(4);

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

        return list;

    }

    public String getCDType(int cdtypeId)
    {
        ResultSet res1=null;
        try
        {

            java.sql.PreparedStatement prepar1 = conn.prepareStatement(
                "select display from CDtype where CDtypeId=?");
            prepar1.setLong(1, cdtypeId);
            res1 = prepar1.executeQuery();
            res1.next();
            return res1.getString("display");
        }
        catch (SQLException ex)
        {

            return null;
        }
    }
    public boolean setCDBean(CDBean cb)
    {
        if (!checkParameter(cb.getCdName() + cb.getCdCompany() + cb.getCdAlbum() +
                            cb.getCdType()))
        {
            return false;
        }

        boolean flag = false;
        String sql =
            "update CDinfo set CDname=?,CDcompany=?,CDalbum=?,CDtypeId=? where CDid=?";
        try
        {
            prepar = conn.prepareStatement(sql);
            prepar.setString(1, cb.getCdName());
            prepar.setString(2, cb.getCdCompany());
            prepar.setString(3, cb.getCdAlbum());
            prepar.setInt(4, Integer.parseInt(cb.getCdType()));
           // prepar.setLong(5, cb.getCdId());
            int result = prepar.executeUpdate();
            if (result > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }

        }
        catch (Exception ex)
        {
            flag = false;
            ex.printStackTrace();
        }
        return flag;
    }

    public CDBean getCDBean(long id)
    {

        CDBean cb = new CDBean();
        int i=1;
        String sql = "select * from CDinfo where CDid=?";
        try
        {
            prepar = conn.prepareStatement(sql);
            prepar.setLong(1, id);
            res = prepar.executeQuery();
            while (res.next())
            {
                cb.setCdAlbum(res.getString("CDalbum"));
                cb.setCdCompany(res.getString("CDcompany"));
                cb.setCdName(res.getString("CDname"));
                cb.setCdId(i);
                cb.setCdType(getCDType(res.getInt("CDtypeId")));

            }
              i++;
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }
        return cb;
    }

    public boolean deleteCDBean(long id)
    {
        boolean flag = false;
        String sql = "delete from CDinfo where CDid=?";
        try
        {
            prepar = conn.prepareStatement(sql);
            prepar.setLong(1, id);
            int result = prepar.executeUpdate();
            if (result > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception ex)
        {
            flag = false;
            ex.printStackTrace();
        }
        return flag;
    }

    public boolean addCDBean(CDBean cb)
    {
        boolean flag = false;
        if (!checkParameter(cb.getCdName() + cb.getCdCompany() + cb.getCdAlbum() + cb.getCdId()+
                            cb.getCdType()))
        {
            return false;
        }
        String sql = "insert into CDinfo values(?,?,?,default,?)";
        try
        {
            this.prepar = conn.prepareStatement(sql);
            prepar.setString(1, cb.getCdName());
            prepar.setString(2, cb.getCdCompany());
            prepar.setString(3, cb.getCdAlbum());
            prepar.setInt(4, Integer.parseInt(cb.getCdType()));
            int result = prepar.executeUpdate();
            if (result > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }

        }
        catch (Exception ex)
        {
            flag = false;
            ex.printStackTrace();
        }
        return flag;
    }

    public boolean setUserBean(UserBean ub)
    {
        boolean flag = false;
        String sql = "update admin set userPwd=? where userId=?";
        try
        {
            if (!checkParameter(ub.getUserPwd()))
            {
                return false;
            }
            this.prepar = conn.prepareStatement(sql);
            prepar.setString(1, ub.getUserPwd());
            prepar.setLong(2, ub.getUserId());
            int result = prepar.executeUpdate();
            if (result > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception ex)
        {
            flag = false;
            ex.printStackTrace();
        }
        return flag;
    }

    public boolean addUserBean(UserBean ub)
    {
        boolean flag = false;
        String sql = "insert into admin(userName,userPwd) values(?,?)";
        //int i=1;
        if (!checkParameter(ub.getUserPwd() + ub.getUserName()+ub.getUserId()))
        {
            return false;
        }
        if (hasUser(ub.getUserName()))
        {
            return false;
        }
        try
        {
            prepar = conn.prepareStatement(sql,prepar.RETURN_GENERATED_KEYS);
            prepar.setString(1, ub.getUserName());
            prepar.setString(2, ub.getUserPwd());
           // prepar.setLong(3,ub.getUserId());
            int result = prepar.executeUpdate();
            if (result > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
          //  i++;

        }
        catch (Exception ex)
        {
            flag = false;
            ex.printStackTrace();
        }

        return flag;
    }

    public boolean hasUser(String userName)
    {
        boolean flag = true;
        String sql = "select count(*) from admin where userName=?";
        try
        {
            prepar = conn.prepareStatement(sql);
            prepar.setString(1, userName);
            res = prepar.executeQuery();
            res.next();
            int result = res.getInt(1);
            if (result > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
            flag = true;
        }

        return flag;
    }


}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T17:37:09+00:00Added an answer on May 28, 2026 at 5:37 pm
    public class DataBean{
        private Connection conn = null;
        private ResultSet res = null;
        // ...
        private Statement stmt=null;
        private java.sql.PreparedStatement prepar = null;
        private java.sql.CallableStatement proc = null;
        // ...
    

    This is wrong. You should not declare them at class level. You should declare them at method level. As an example, I’ll take your getUser() method, it must look like this:

    public UserBean getUser(String userName) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        // ...
    

    Then, you need to ensure that you close the resources in the finally block in the reversed order as you’ve acquired them in the very same try block. Here’s a complete rewrite of your getUser() method according the recommended JDBC idiom:

    public UserBean getUser(String userName) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        UserBean userBean = null;
    
        String sql = "select userId, userName, userPwd from admin where userName = ?";
    
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(sql);
            statement.setString(1, userName);
            resultSet = statement.executeQuery();
    
            if (resultSet.next()) {
                userBean = new UserBean();
                userBean.setUserId(resultSet.getInt("userId");
                userBean.setUserName(resultSet.getString("userName"));
                userBean.setUserPwd(resultSet.getString("userPwd"));
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }
    
        return userBean;
    }
    

    (note that I fixed the user ID to be a database column field, make it an auto incremental PK, also note that I fixed the while to be an if -there is only 1 user with this name, right?-, also note that it returns null when there’s no known user which allows for easy checking afterwards)

    See also:

    • How often should Connection, Statement and ResultSet be closed in JDBC?
    • JDBC MySql connection pooling practices to avoid exhausted connection pool
    • Am I Using JDBC Connection Pooling?

    Your checkUsersLogin() and checkParameter() approaches are also fishy, but that’s subject for a different question.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

these below codes give whole data of my Rehber datas. But if i want
I have an operation I'd like to run for each row of a data
I've got a whole bunch of data being displayed in different Labels, now I'm
I have a data warehouse containing typical star schemas, and a whole bunch of
I want to be able to access some device specific data while running an
I have got around 800 files of maximum 55KB-100KB each where the data is
I have a list of floating point data in which I want to find
In Java I want to create a file from and save the data on
I wrote a storable vector instance for the data type below ( original question
I am using csv.reader to read file but it giving me whole file. file_data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.