Example usage for java.sql ResultSet getString

List of usage examples for java.sql ResultSet getString

Introduction

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

Prototype

String getString(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.

Usage

From source file:net.tirasa.ilgrosso.resetdb.Main.java

private static void resetSQLServer(final Connection conn) throws SQLException {

    Statement statement = conn.createStatement();
    final ResultSet resultSet = statement.executeQuery("SELECT sysobjects.name " + "FROM sysobjects "
            + "JOIN sysusers " + "ON sysobjects.uid = sysusers.uid "
            + "WHERE OBJECTPROPERTY(sysobjects.id, N'IsView') = 1");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add("DROP VIEW " + resultSet.getString(1));
    }/*from w  w  w.jav a 2  s. com*/
    resultSet.close();
    statement.close();

    statement = conn.createStatement();
    for (String drop : drops) {
        statement.executeUpdate(drop);
    }
    statement.close();

    statement = conn.createStatement();
    statement.executeUpdate("EXEC sp_MSforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"");
    statement.close();

    statement = conn.createStatement();
    statement.executeUpdate("EXEC sp_MSforeachtable \"DROP TABLE ?\"");
    statement.close();

    conn.close();
}

From source file:FacultyAdvisement.StudentRepository.java

public static Student readById(DataSource ds, String key) throws SQLException {
    String studentSQL = "SElECT * FROM STUDENT WHERE STUID = ?";
    Student student = new Student();

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }/*from  w  w  w.j  a  va 2s  . c  o  m*/

    Connection conn = ds.getConnection();

    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }

    try {

        PreparedStatement sqlStatement = conn.prepareStatement(studentSQL);

        sqlStatement.setString(1, key);

        ResultSet result = sqlStatement.executeQuery();
        while (result.next()) {
            student.setId(key);
            student.setFirstName(result.getString("firstname"));
            student.setLastName(result.getString("lastname"));
            student.setMajorCode(result.getString("majorcode"));
            student.setPhoneNumber(result.getString("phone"));
            student.setUsername(result.getString("email"));

        }

    } finally {
        conn.close();
    }

    return student;
}

From source file:com.sql.CaseType.java

/**
 * Gathers a list of active case types for finding the proper section based 
 * on the case number./* w w  w. jav  a2s . c o m*/
 * 
 * @return List CaseTypeModel
 */
public static List<CaseTypeModel> getCaseTypes() {
    List<CaseTypeModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM CaseType WHERE active = 1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            CaseTypeModel item = new CaseTypeModel();
            item.setId(rs.getInt("id"));
            item.setActive(rs.getBoolean("active"));
            item.setSection(rs.getString("Section"));
            item.setCaseType(rs.getString("caseType"));
            item.setDescription(rs.getString("Description"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:Emporium.Controle.ContrVpne.java

public static ArrayList<Vpne> listaVpne(String where, String nomeBD, int idCli) {

    String sql = "SELECT * FROM vpne WHERE idCliente = " + idCli + " ";
    sql = sql + where + " ;";
    Connection conn = Conexao.conectar(nomeBD);
    ArrayList<Vpne> listaVpne = new ArrayList<Vpne>();

    try {//from  w w w  .ja v  a  2 s  .co m
        PreparedStatement valores = conn.prepareStatement(sql);
        valores.executeQuery();
        ResultSet result = (ResultSet) valores.executeQuery();

        while (result.next()) {

            int idCliente = result.getInt("idCliente");
            int idDepartamento = result.getInt("idDepartamento");
            String nomeDepto = result.getString("nomeDepartamento");

            String sro = result.getString("sro");
            String descricao = result.getString("descricao");
            String valor = result.getString("valor");

            String remetente = result.getString("remetente");
            String cnpj_remetente = result.getString("cnpj_remetente");
            String rlogradouro = result.getString("rlogradouro");
            String rnumero = result.getString("rnumero");
            String rbairro = result.getString("rbairro");
            String rcidade = result.getString("rcidade");
            String ruf = result.getString("ruf");

            String destinatario = result.getString("destinatario");
            String cpf_cnpj_dest = result.getString("cpf_cnpj_dest");
            String dlogradouro = result.getString("dlogradouro");
            String dnumero = result.getString("dnumero");
            String dbairro = result.getString("dbairro");
            String dcidade = result.getString("dcidade");
            String dcep = result.getString("dcep");
            String duf = result.getString("duf");

            String data = result.getString("data");

            Destinatario remVpne = new Destinatario(remetente, cnpj_remetente, rlogradouro, rnumero, rbairro,
                    rcidade, ruf);
            Destinatario destVpne = new Destinatario(destinatario, cpf_cnpj_dest, dlogradouro, dnumero, dbairro,
                    dcidade, dcep, duf);

            Vpne vp = new Vpne(sro, descricao, valor, idCliente, idDepartamento, nomeDepto, data, remVpne,
                    destVpne);
            listaVpne.add(vp);
        }
        valores.close();
        return listaVpne;
    } catch (SQLException e) {
        Logger.getLogger(ContrVpne.class.getName()).log(Level.WARNING, e.getMessage(), e);
        return listaVpne;
    } finally {
        Conexao.desconectar(conn);
    }
}

From source file:bullioneconomy.bullionchart.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return The dataset./*from w w  w.  j  a  v a 2  s .c o m*/
 */
private static XYDataset createDataset() throws ClassNotFoundException, SQLException, ParseException {

    TimeSeries s1 = new TimeSeries("Actual", Day.class);
    TimeSeries s2 = new TimeSeries("Forecasted", Day.class);
    Class.forName("com.mysql.jdbc.Driver");
    try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/BULLION", "yajnab",
            "petrol123")) {
        Statement stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("SELECT * FROM gold");
        ArrayList<Double> arm = new ArrayList<>();
        predictor pcd = new predictor();
        arm = pcd.ARIMApredict();
        int i = 0;
        while (result.next()) {

            String datefeed = result.getString(1);
            Double value = result.getDouble(2);
            int[] m = new int[3];
            //bullionchart bcc = new bullionchart();
            //m = bcc.dateget(datefeed);
            m = dateget(datefeed);
            s1.add(new Day(m[0], m[1], m[2]), value);
            s2.add(new Day(m[0], m[1], m[2]), arm.get(i));
            i++;
        }
        result.close();
        /*s1.add(new Month(2, 2001), 181.8);
        s1.add(new Month(3, 2001), 167.3);
        s1.add(new Month(4, 2001), 153.8);
        s1.add(new Month(5, 2001), 167.6);
        s1.add(new Month(6, 2001), 158.8);
        s1.add(new Month(7, 2001), 148.3);
        s1.add(new Month(8, 2001), 153.9);
        s1.add(new Month(9, 2001), 142.7);
        s1.add(new Month(10, 2001), 123.2);
        s1.add(new Month(11, 2001), 131.8);
        s1.add(new Month(12, 2001), 139.6);
        s1.add(new Month(1, 2002), 142.9);
        s1.add(new Month(2, 2002), 138.7);
        s1.add(new Month(3, 2002), 137.3);
        s1.add(new Month(4, 2002), 143.9);
        s1.add(new Month(5, 2002), 139.8);
        s1.add(new Month(6, 2002), 137.0);
        s1.add(new Month(7, 2002), 132.8);*/
    }

    /*TimeSeries s2 = new TimeSeries("Forecasted", Month.class);
    s2.add(new Month(2, 2001), 129.6);
    s2.add(new Month(3, 2001), 123.2);
    s2.add(new Month(4, 2001), 117.2);
    s2.add(new Month(5, 2001), 124.1);
    s2.add(new Month(6, 2001), 122.6);
    s2.add(new Month(7, 2001), 119.2);
    s2.add(new Month(8, 2001), 116.5);
    s2.add(new Month(9, 2001), 112.7);
    s2.add(new Month(10, 2001), 101.5);
    s2.add(new Month(11, 2001), 106.1);
    s2.add(new Month(12, 2001), 110.3);
    s2.add(new Month(1, 2002), 111.7);
    s2.add(new Month(2, 2002), 111.0);
    s2.add(new Month(3, 2002), 109.6);
    s2.add(new Month(4, 2002), 113.2);
    s2.add(new Month(5, 2002), 111.6);
    s2.add(new Month(6, 2002), 108.8);
    s2.add(new Month(7, 2002), 101.6);*/

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);
    dataset.addSeries(s2);

    dataset.setDomainIsPointsInTime(true);

    return dataset;

}

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Drop all tables from database with connection c. Specific to MySQL
 * databases./*w  ww  .  j  av a2  s  .  c o m*/
 * 
 * @param c
 * @param driver 
 * @throws SQLException
 */
public static void resetMySQLDatabase(Connection c, DriverType driver) throws SQLException {
    // Get tables of database
    DatabaseMetaData meta = c.getMetaData();
    ResultSet tablesSet = meta.getTables(c.getCatalog(), null, "%", null);
    while (tablesSet.next()) {
        // Extract table name
        String tableName = new String(tablesSet.getString("TABLE_NAME"));
        String tableType = tablesSet.getString("TABLE_TYPE");
        // Get a statement from the connection
        Statement stmt = c.createStatement();
        // Execute the query
        if (driver == DriverType.MysqlDriver) {
            // MySQL compatibility
            stmt.execute("SET FOREIGN_KEY_CHECKS = 0");
            stmt.execute("DROP TABLE \"" + tableName + "\"");
        } else {
            if (tableType != null && tableType.equals("TABLE"))
                stmt.execute("DROP TABLE \"" + tableName + "\" CASCADE");
        }
        stmt.close();
    }
}

From source file:com.jaspersoft.studio.data.xvia.querydesigner.TrackViaMetadata.java

public static List<String> readTableTypes(DatabaseMetaData meta) throws SQLException {
    List<String> tableTypes = new ArrayList<String>();
    ResultSet rs = meta.getTableTypes();
    while (rs.next())
        tableTypes.add(rs.getString("TABLE_TYPE")); //$NON-NLS-1$
    rs.close();//from w  w  w  .java 2s . c  om
    return tableTypes;
}

From source file:luceneindexdemo.LuceneIndexDemo.java

public static void searchIndex(String s) throws IOException, ParseException, SQLException,
        FileNotFoundException, org.json.simple.parser.ParseException {

    Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY);
    IndexReader reader = IndexReader.open(directory);
    IndexSearcher search = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    QueryParser queryparser = new QueryParser(FIELD_CONTENTS, analyzer);
    Query query = queryparser.parse(s);
    Hits hits = search.search(query);/*from   ww  w . j  ava 2 s  .  co  m*/
    Iterator<Hit> it = hits.iterator();
    //System.out.println("hits:"+hits.length());
    float f_score;
    List<String> names = new ArrayList<>();
    while (it.hasNext()) {
        Hit hit = it.next();
        f_score = hit.getScore();

        //System.out.println(f_score);
        Document document = hit.getDocument();
        Field f = document.getField(FIELD_PATH);

        //System.out.println(f.readerValue());
        //System.out.println(document.getValues(FIELD_PATH));
        String path = document.get(FIELD_PATH);
        System.out.println(document.getValues(path));
        Field con = document.getField(FIELD_PATH);
        //System.out.println("hit:"+path+" "+hit.getId()+" "+con);
        names.add(new File(path).getName());
    }

    //ProcessBuilder pb=new ProcessBuilder();
    FileReader fReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/inntell.json");
    JSONParser jsParser = new JSONParser();
    //System.out.println("This is an assumption that you belong to US");
    FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json");
    Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
    System.out.println(names);
    if (names.get(0).equals("miss")) {

        System.out.println(s);
        StringTokenizer stringTokenizer = new StringTokenizer(s);
        Connection con1 = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
        String querySearch = "match ()-[r:KNOWS]-() where has(r.relType) return distinct r.relType";
        ResultSet rSet = con.createStatement().executeQuery(querySearch);
        List<String> allRels = new ArrayList<>();
        while (rSet.next()) {
            System.out.println();
            allRels.add(rSet.getString("r.relType"));
        }
        //System.out.println(rSet);

        while (stringTokenizer.hasMoreTokens()) {
            String next = stringTokenizer.nextToken();
            if (allRels.contains(next)) {
                missOperation(next);
            }
            //System.out.println(resSet.getString("r.relType"));

        }
        System.out.println(names.get(1));
        //missOperation(names.get(1));
    } else {
        try {
            JSONObject jsonObj = (JSONObject) jsParser.parse(fReader);
            System.out.println(names.get(0));

            JSONObject jsObj = (JSONObject) jsonObj.get(names.get(0));
            JSONObject results = new JSONObject();
            System.out.println(jsObj.get("explaination"));
            results.put("explaination", jsObj.get("explaination"));
            JSONArray reqmts = (JSONArray) jsObj.get("true");
            System.out.println("Let me look out for the places that contains ");
            List<String> lis = new ArrayList<>();
            JSONObject locObj = (JSONObject) jsParser.parse(freReader);
            JSONArray jsArray = (JSONArray) locObj.get("CHENNAI");
            Iterator<JSONArray> ite = reqmts.iterator();
            int k = 0;
            String resQuery = "START n=node:restaurant('withinDistance:[" + jsArray.get(0) + ","
                    + jsArray.get(1) + ",7.5]') where";
            Iterator<JSONArray> ite1 = reqmts.iterator();
            while (ite1.hasNext())
                System.out.println(ite1.next());

            while (ite.hasNext()) {
                lis.add("n.type=" + "'" + ite.next() + "'");
                if (k == 0)
                    resQuery += " " + lis.get(k);
                else
                    resQuery += " or " + lis.get(k);
                //System.out.println(attrib);
                k++;

            }
            resQuery += " return n.name,n.place,n.type";
            File writeTo = new File(
                    "/home/rishav12/NetBeansProjects/LuceneIndexDemo/filestoIndex1/" + names.get(0));
            FileOutputStream fop = new FileOutputStream(writeTo, true);
            String writeTOFile = s + "\n";
            fop.write(writeTOFile.getBytes());
            //System.out.println(resQuery);
            ResultSet res = con.createStatement().executeQuery(resQuery);
            JSONArray resSet = new JSONArray();

            while (res.next()) {
                System.out.println(" name:" + res.getString("n.name") + " located:" + res.getString("n.place")
                        + " type:" + res.getString("n.type"));
                JSONObject jsPart = new JSONObject();
                jsPart.put("name", res.getString("n.name"));
                jsPart.put("located", res.getString("n.place"));
                jsPart.put("type", res.getString("n.type"));
                resSet.add(jsPart);
            }
            results.put("results", resSet);
            File resultFile = new File("result.json");
            FileOutputStream fop1 = new FileOutputStream(resultFile);
            System.out.println(results);
            fop1.write(results.toJSONString().getBytes());
            //String resQuery="START n=node:restaurant('withinDistance:[40.7305991, -73.9865812,10.0]') where n.coffee=true return n.name,n.address;";
            //System.out.println("Sir these results are for some coffee shops nearby NEW YORK");
            //ResultSet res=con.createStatement().executeQuery(resQuery);
            //while(res.next())
            //System.out.println("name: "+res.getString("n.name")+" address: "+res.getString("n.address"));
        } catch (org.json.simple.parser.ParseException ex) {
            Logger.getLogger(LuceneIndexDemo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:com.sql.Activity.java

/**
 * Gathers a list of tiles that are awaiting a timestamp
 * // w ww .java2 s .  c  o m
 * @return List (ActivityModel)
 */
public static List<ActivityModel> getFilesToStamp() {
    List<ActivityModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM Activity WHERE awaitingTimestamp = 1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            ActivityModel type = new ActivityModel();
            type.setId(rs.getInt("id"));
            type.setCaseYear(rs.getString("caseYear"));
            type.setCaseType(rs.getString("caseType"));
            type.setCaseMonth(rs.getString("caseMonth"));
            type.setCaseNumber(rs.getString("caseNumber"));
            type.setDate(rs.getTimestamp("date"));
            type.setFileName(rs.getString("fileName"));
            list.add(type);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:Main.java

private static void outputResultSet(ResultSet rs) throws Exception {
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numberOfColumns = rsMetaData.getColumnCount();
    for (int i = 1; i < numberOfColumns + 1; i++) {
        String columnName = rsMetaData.getColumnName(i);
        System.out.print(columnName + "   ");

    }//from  ww w.j  a v  a 2 s . c o  m
    System.out.println();
    System.out.println("----------------------");

    while (rs.next()) {
        for (int i = 1; i < numberOfColumns + 1; i++) {
            System.out.print(rs.getString(i) + "   ");
        }
        System.out.println();
    }

}