Example usage for java.sql ResultSet getRow

List of usage examples for java.sql ResultSet getRow

Introduction

In this page you can find the example usage for java.sql ResultSet getRow.

Prototype

int getRow() throws SQLException;

Source Link

Document

Retrieves the current row number.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    try {//from w  w  w  .  ja v  a2  s .com
        String url = "jdbc:odbc:yourdatabasename";
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String user = "guest";
        String password = "guest";

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);

        Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        String sqlQuery = "SELECT EMPNO, EName, Job, MGR, HIREDATE FROM EMP";

        ResultSet rs = stmt.executeQuery(sqlQuery);

        int rowSize = 0;
        while (rs.next()) {
            rowSize++;
        }

        System.out.println("Number of Rows in ResultSet is: " + rowSize);
        if (rowSize == 0) {
            System.out.println("Since there are no rows, exiting...");
            System.exit(0);
        }

        int cursorPosition = Math.round(rowSize / 2);

        System.out.println("Moving to position: " + cursorPosition);
        rs.absolute(cursorPosition);
        System.out.println("Name: " + rs.getString(2));

        rs.relative(-1);

        cursorPosition = rs.getRow();
        System.out.println("Moving to position: " + cursorPosition);
        System.out.println("Name: " + rs.getString(2));

        System.out.println("Moving to the first row");
        while (!rs.isFirst()) {
            rs.previous();
        }
        System.out.println("Name: " + rs.getString(2));
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:InsertRowBug.java

public static void main(String args[]) {

    String url;//  w  ww  .j a va 2  s  .  c o  m
    // url = "jdbc:odbc:SQL Anywhere 5.0 Sample";
    // url = "jdbc:oracle:thin:@server:1521:db570";
    url = "jdbc:odbc:RainForestDSN";

    String driver;
    //driver = "oracle.jdbc.driver.OracleDriver";
    driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    String user, pass;
    user = "student";
    pass = "student";

    Connection con;
    Statement stmt;
    ResultSet uprs;

    try {
        Class.forName(driver);

    } catch (java.lang.ClassNotFoundException e) {
        System.err.println(e);
        return;
    }

    try {
        con = DriverManager.getConnection(url, user, pass);
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        uprs = stmt.executeQuery("SELECT * FROM Music_Recordings");

        // Check the column count
        ResultSetMetaData md = uprs.getMetaData();
        System.out.println("Resultset has " + md.getColumnCount() + " cols.");

        int rowNum = uprs.getRow();
        System.out.println("row1 " + rowNum);
        uprs.absolute(1);
        rowNum = uprs.getRow();
        System.out.println("row2 " + rowNum);
        uprs.next();
        uprs.moveToInsertRow();
        uprs.updateInt(1, 150);
        uprs.updateString(2, "Madonna");
        uprs.updateString(3, "Dummy");
        uprs.updateString(4, "Jazz");
        uprs.updateString(5, "Image");
        uprs.updateInt(6, 5);
        uprs.updateDouble(7, 5);
        uprs.updateInt(8, 15);
        uprs.insertRow();
        uprs.close();
        stmt.close();
        con.close();
    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:at.molindo.dbcopy.util.Utils.java

public static void printRow(ResultSet pk) throws SQLException {
    System.out.println("--- " + pk.getRow() + ". row ---");
    for (int i = 1; i <= pk.getMetaData().getColumnCount(); i++) {
        System.out.println(pk.getMetaData().getColumnName(i) + ": " + pk.getObject(i));
    }/*  w  ww .j  av  a  2  s . c o  m*/
}

From source file:ScrollableRs.java

public static void printRow(ResultSet rs) throws SQLException {
    int ssn = rs.getInt("ssn");
    String name = rs.getString("name");
    double salary = rs.getDouble("salary");

    System.out.print("Row Number=" + rs.getRow());
    System.out.print(", SSN: " + ssn);
    System.out.print(", Name: " + name);
    System.out.println(", Salary: $" + salary);
}

From source file:UpdateableRs.java

public static void printRs(ResultSet rs) throws SQLException {
    rs.beforeFirst();//from   ww w  .  j  a  v  a2 s. com

    while (rs.next()) {
        int ssn = rs.getInt("ssn");
        String name = rs.getString("name");
        double salary = rs.getDouble("salary");

        System.out.print("Row Number=" + rs.getRow());
        System.out.print(", SSN: " + ssn);
        System.out.print(", Name: " + name);
        System.out.println(", Salary: $" + salary);
    }
    System.out.println();
}

From source file:com.example.querybuilder.server.Jdbc.java

public static int getRow(ResultSet resultSet) {
    try {//from   w  ww. j  a  v a 2 s .c  o  m
        int row = resultSet.getRow();
        return row;
    } catch (SQLException e) {
        throw new SqlRuntimeException(e);
    }
}

From source file:agendavital.modelo.data.Noticia.java

/**
 * Funcion que inserta la noticia en la BD
 *
 * @param titulo//from  w w w .ja va  2 s  .co  m
 * @param link
 * @param fecha
 * @param categoria
 * @param cuerpo
 * @param tags
 * @return
 * @throws agendavital.modelo.excepciones.ConexionBDIncorrecta
 * @throws java.sql.SQLException
 */
public static Noticia Insert(String titulo, String link, String fecha, String categoria, String cuerpo,
        ArrayList<String> tags) throws ConexionBDIncorrecta, SQLException {
    int nuevoId = 0;
    try (Connection conexion = ConfigBD.conectar()) {
        String insert = "INSERT INTO noticias (titulo, link, fecha, categoria, cuerpo)";
        insert += String.format(" VALUES (%s, %s, %s, %s, %s)", ConfigBD.String2Sql(titulo, false),
                ConfigBD.String2Sql(link, false), ConfigBD.String2Sql((fecha), false),
                ConfigBD.String2Sql(categoria, false), ConfigBD.String2Sql(cuerpo, false));
        int executeUpdate = conexion.createStatement().executeUpdate(insert);
        nuevoId = ConfigBD.LastId("noticias");
        for (String tag : tags) {
            String consultaTag = String.format("SELECT id_etiqueta from etiquetas WHERE Nombre = %s;",
                    ConfigBD.String2Sql(tag, false));
            ResultSet rs = conexion.createStatement().executeQuery(consultaTag);
            rs.next();
            int idTag = (rs.getRow() == 1) ? rs.getInt("id_etiqueta") : -1;
            if (idTag == -1) {
                String insertTag = String.format("INSERT INTO etiquetas (nombre) VALUES (%s);",
                        ConfigBD.String2Sql(tag, false));
                conexion.createStatement().executeUpdate(insertTag);
                idTag = ConfigBD.LastId("etiquetas");
            }
            String insertNoticiaEtiqueta = String.format(
                    "INSERT INTO momentos_noticias_etiquetas (id_noticia, id_etiqueta) VALUES(%d, %d);",
                    nuevoId, idTag);
            conexion.createStatement().executeUpdate(insertNoticiaEtiqueta);
        }
    } catch (SQLException e) {
    }
    return new Noticia(nuevoId);
}

From source file:com.autentia.tnt.bill.migration.support.OriginalInformationRecoverer.java

/**
 * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*from ww w.  ja v a  2  s .  c  o m*/
 */
public static Date[] getFechaFacturaOriginal(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    Date[] result = new Date[0];

    try {
        log.info("RECOVERING FECHAS " + billType + " ORIGINALES");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS vacia
        String sql = "SELECT date_add(creationDate, INTERVAL expiration DAY) as date FROM Bill B where billType = ? order by date";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

        rs.last();
        result = new Date[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDate(1);
            log.info("\t" + result[counter]);
            counter++;
        }
        con.commit();
    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }
    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la fecha de pago o cobro de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura/*from  w  w  w. jav a  2  s.c  o  m*/
 */
public static Date[] getFechaFacturaMigrated(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    Date[] result = new Date[0];

    try {
        log.info("RECOVERING FECHAS " + billType + " MIGRADAS");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); //NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS vacio.

        String sql = "SELECT bp.expirationDate FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by bp.expirationDate";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);

        rs = pstmt.executeQuery();

        rs.last();
        result = new Date[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDate(1);
            log.info("\t" + result[counter]);
            counter++;
        }

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

/**
 * Recupera la suma total de todos los conceptos de cada una de las facturas cuyo tipo se envia por parametro
 * @param billType tipo de factura// w w w  .j av a2 s. c  o  m
 */
public static double[] getImporteFacturaMigrated(String billType) throws Exception {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    LineNumberReader file = null;
    double[] result = new double[0];

    try {
        log.info("RECOVERING IMPORTE FACTURAS " + billType + " MIGRADAS");

        // connect to database
        Class.forName(BillToBillPaymentMigration.DATABASE_DRIVER);
        con = DriverManager.getConnection(BillToBillPaymentMigration.DATABASE_CONNECTION,
                BillToBillPaymentMigration.DATABASE_USER, BillToBillPaymentMigration.DATABASE_PASS); // NOSONAR
        con.setAutoCommit(false); // DATABASE_PASS vacio         

        String sql = "SELECT bp.amount FROM BillPayment bp, Bill b where bp.billId = b.id and b.billType = ? order by amount";

        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, billType);
        rs = pstmt.executeQuery();

        rs.last();
        result = new double[rs.getRow()];
        rs.beforeFirst();
        int counter = 0;

        while (rs.next()) {
            result[counter] = rs.getDouble(1);
            log.info("\t" + result[counter]);
            counter++;
        }

    } catch (Exception e) {
        log.error("FAILED: WILL BE ROLLED BACK: ", e);
        if (con != null) {
            con.rollback();
        }

    } finally {
        cierraFichero(file);
        liberaConexion(con, pstmt, rs);
    }
    return result;
}