如何将My ResultSet移动到特定记录

时间:2015-08-19 17:48:48

标签: java mysql jdbc

我在移动ResultSet当前记录时遇到了一些麻烦。

我正在学习JDBC,而且我来自Clipper和Delphi。所以我曾经有某种“引用”,比如记录号或对“标记”记录的引用,所以我可以保存这个引用并稍后再回到这个位置。 在尝试使用JDBC和MySql时,我尝试使用select / where语句来获取我想要的记录。没关系。但是当我尝试获取记录的行时,碰巧在ResultSet中只有一行(我意识到它甚至可以在我编写代码之前发生,但我必须测试,因为它是你学习的方式。 :))

所以,简而言之。我需要一种方法来通过某些值“找到”一条记录,比如主键(选择/可能在哪里)和“保存”这个位置。所以我可以将数据库移动到同一个记录,但是有大量数据(不仅仅是过滤后的数据)。 我可以做一段时间(next())或者使用一些sql代码来使我的表单以不同的方式工作。但这不是我的目标。

因此。谁有关于如何做到这一点的一些提示?那是我的DAO课程。我希望方法“findCod”将我的ResultSet移动到rsConsulta中的相同记录。

DAO班级:

    package control;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import javax.sql.rowset.FilteredRowSet;
    import javax.swing.JOptionPane;
    import model.Pais;

    /**
     *
     * @author X8
     */
    public class PaisDAO extends GenericDAO<Pais> {

        private Connection conn;
        private PreparedStatement ps;
        private ResultSet rollRs;

        private final String SELECT_QUERY="select * from paises";

        public PaisDAO() {
        }

        /**
         * Cria a conexao e retorna a mesma.
         * @return
         * @throws SQLException 
         */
        @Override
        public Connection getConnection() {
            return conn;
        }

        /**
         * @param conn 
         */
        @Override
        public void startConnection(Connection conn)  {
            this.conn=conn;

        } //startConnection

        /**
         * @throws SQLException 
         */
        @Override
        public void startDataSet() throws SQLException{
            ps=conn.prepareStatement(SELECT_QUERY, 
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            rollRs=ps.executeQuery();
        }


        @Override
        public void novo(Pais p) throws SQLException{

            try {

                rollRs.moveToInsertRow(); //nova linha
                rollRs.updateInt("pais", p.getPais());
                rollRs.updateString("abreviado", p.getAbreviado());
                rollRs.updateString("descricao",p.getDescricao());
                rollRs.updateString("icone",p.getIcone());
                rollRs.insertRow(); //Salva as alteracoes.
                rollRs.moveToCurrentRow();


            } catch (SQLException e) {
                throw new SQLException(e.getMessage());
            }

        } //fim novo pais

        @Override
        public void altera(Pais p) throws SQLException{
            try {

                rollRs.updateInt("pais", p.getPais());
                rollRs.updateString("abreviado", p.getAbreviado());
                rollRs.updateString("descricao",p.getDescricao());
                rollRs.updateString("icone",p.getIcone());
                rollRs.updateRow();
                rollRs.moveToCurrentRow();
            } catch (SQLException e) {
                throw new SQLException(e.getMessage());
            }

        }

        public void filtra(String filtro) throws SQLException{
            rollRs=ps.executeQuery(SELECT_QUERY+" where "+filtro);

        }

        public String filtraPais(int ...pais) throws SQLException{
            String query="(";
            int cont=0;
            for (int p:pais){
                query+="(pais="+Integer.toString(p)+") ";
                cont++;
                if (cont<pais.length)
                    query+="or ";
            }
            query+=")";
            filtra(query);
            return query;
        }


        @Override
        public void exclui() throws SQLException{
            rollRs.deleteRow();
            rollRs.moveToCurrentRow();
        }

        /**
         *
         * @return
         * @throws SQLException
         */
        @Override
        public int getRow() throws SQLException{
            return rollRs.getRow();
        }
        /**
         * 
         * @param row
         * @return
         * @throws SQLException 
         */
        @Override
        public int goToRow(int row) throws SQLException{
            int oldRow=getRow();
            rollRs.absolute(row);
            return oldRow;
        }
        /**
         * 
         * @throws SQLException 
         */
        @Override
        public void first() throws SQLException{
            rollRs.first();
        }
        /**
         * 
         * @throws SQLException 
         */
        @Override
        public void last() throws SQLException {
            rollRs.last();
        }

        @Override
        public void previous() throws SQLException{
            if (rollRs.isBeforeFirst()){
                rollRs.first();
            } else {
                rollRs.previous();
            }
        }
        /**
         * 
         * @throws SQLException 
         */
        @Override
        public void next() throws SQLException{
            if (rollRs.isAfterLast()){
                rollRs.last();
            } else {
                rollRs.next();
            }
        }

        /**
         * Retorna objeto no registro atual
         * @return 
         * @throws java.sql.SQLException 
         */
        @Override
        public Pais getCurrent() throws SQLException {
            Pais p=new Pais();

            p.setPais(rollRs.getInt("Pais"));
            p.setDescricao(rollRs.getString("Descricao"));
            p.setAbreviado(rollRs.getString("Abreviado"));
            p.setIcone(rollRs.getString("Icone"));
            return p;
        }

        /**
         * Fecha todas as conexoes e datasets
         * @throws SQLException 
         */    
        @Override
        public void closeAll() throws SQLException {
            try {

                if (!rollRs.isClosed())
                    rollRs.close();
                if (!ps.isClosed())
                    ps.close();
                if (!conn.isClosed())
                    conn.close();

            } catch (SQLException e) {
                throw new SQLException(e.getMessage());

            }

        } //fim closeAll

        public ArrayList<Pais> asArrayList() throws SQLException{
            ArrayList <Pais> aPais=new ArrayList<>();
            first();
            aPais.add(getCurrent());
            while (rollRs.next()){
                aPais.add(getCurrent());

            }

            return aPais;
        }

        public String[] getColumnNames(){
            String[] nomes={"Pais","Abrev","Descrição","Icone"};


            return nomes;
        }

        public void findCod(Pais p) throws SQLException{
            int codPais=p.getPais();
            PreparedStatement psConsulta=conn.prepareStatement(SELECT_QUERY+" 
where pais=?", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            psConsulta.setInt(1, codPais);
            ResultSet rsConsulta=psConsulta.executeQuery();


            rsConsulta.first();
            //JOptionPane just for debug 
            JOptionPane.showMessageDialog(null, "Line 
number"+rsConsulta.getRow());
            //there we suposed to move the rollRs dataset to the same record  
of rsConsulta
            goToRow(rsConsulta.getRow());  //always go to line 1.




        }
    } //EOF

先谢谢。我希望我能让它变得容易理解。

2 个答案:

答案 0 :(得分:0)

假设您的表有一个主键,然后在代码中保留pk id的副本,当您需要稍后再次检索或更新该行时,执行'select * from x where id =?'检索它,或'更新...其中id =?'

答案 1 :(得分:0)

您的ResultSet将只包含您执行的SQL查询所选择的行。

如果查询为SELECT * FROM paises,则所有行将从数据库传输到您的程序。

如果查询为SELECT * FROM paises WHERE pais=?,则仅选择与条件匹配的行。然后,您无法导航ResultSet以获取其他行,您将不得不执行另一个查询。

通常,您永远不会想要所有行(可能代码表除外)。您应该查询要查看的行。

要更新行,您有两种选择:

  1. 执行UPDATE SQL语句。
  2. 使用可更新的SELECT为要更新的行执行ResultSet语句,设置值并调用updateRow()
  3. 要插入新行,请执行INSERT SQL语句。您不希望为此使用可更新的ResultSet,因为您必须首先执行虚拟SELECT,这样效率很低。

    此外,您可能需要查看CachedRowSet,以便以断开连接的方式处理数据。