Java Code Examples for java.sql.ResultSet.next()

The following are Jave code examples for showing how to use next() of the java.sql.ResultSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: avengers-db   File: HeroDAO.java   View Source Code Vote up 6 votes
public Hero findHeroesById(String term) throws SQLException {

		String query = "SELECT h.id, h.name, h.sex, i.name AS real_name, m.name AS movies_name, t.team_name AS team_name, h.picture, h.abilities, h.history, t.picture "
				+ "FROM heroes h LEFT JOIN movie_hero mh ON h.id = mh.id_hero "
				+ "LEFT JOIN movie m ON mh.id_movie = m.id " + "LEFT JOIN team_hero th ON th.hero_id = h.id "
				+ "LEFT JOIN team t ON t.team_id = th.team_id " + "LEFT JOIN irl i ON i.hero_id = h.id "
				+ "WHERE h.id='"+term +"'";

		Connection connect = connectToMySQL();
		Statement statement = connect.createStatement();
		ResultSet resultSet = statement.executeQuery(query);
		if (resultSet.next()){
			Hero hero = resultSetToHero(resultSet);
			connect.close();
			return hero;
		}
		else{
			connect.close();
			return null;
		}


	}
 
Example 2
Project: SistemaAlmoxarifado   File: EntradaItemDAO.java   View Source Code Vote up 6 votes
public static ArrayList<EntradaItem> retreaveByEntrada(int entradaId) throws SQLException {
    Statement stm
            = Database.createConnection().
                    createStatement();
    String sql = "SELECT * FROM entrada_itens where entrada = " + entradaId;
    ResultSet rs = stm.executeQuery(sql);
    ArrayList<EntradaItem> entrada = new ArrayList<>();
    while (rs.next()) {
        entrada.add(new EntradaItem(
                rs.getInt("id"),
                ProdutoDAO.retreave(rs.getInt("produto")),
                rs.getInt("entrada"),
                rs.getDouble("quantidade"),
                rs.getTimestamp("validade"),
                rs.getString("lote"),
                rs.getDouble("valor_unitario")));
    }
    rs.next();
    return entrada;
}
 
Example 3
Project: vertx-generator   File: ConfigUtil.java   View Source Code Vote up 6 votes
/**
 * 获得Template配置文件信息
 * 
 * @return
 * @throws Exception
 */
public static TemplateConfig getTemplateConfig(String name) throws Exception {
	Connection conn = null;
	Statement stat = null;
	ResultSet rs = null;
	try {
		conn = getConnection();
		stat = conn.createStatement();
		String sql = String.format("select * from TemplateConfig where name='%s'", name);
		ResultSet resultSet = stat.executeQuery(sql);
		while (resultSet.next()) {
			TemplateConfig result = JSON.parseObject(resultSet.getString("value"), TemplateConfig.class);
			return result;
		}
	} finally {
		if (rs != null)
			rs.close();
		if (stat != null)
			stat.close();
		if (conn != null)
			conn.close();
	}
	return null;
}
 
Example 4
Project: sgroup   File: ProductDaoImpl.java   View Source Code Vote up 6 votes
/**
 * 从数据库查询结果中获取product
 * @param rs 查询结果集
 * @return 返回查询到的产品,否则返回null
 */
private Product getOneProduct(ResultSet rs) {
    Product product = null;
    try {
        if(rs.next()) {
            product = new Product();
            product.setProductId(rs.getInt("pid"));
            product.setProductName(rs.getString("pname"));
            product.setProductPrice(rs.getInt("pprice"));
            product.setNumber(rs.getInt("pnumber"));
            product.setProductTime(rs.getTime("producttime"));
            product.setId(rs.getInt("id"));
            ProductType productType = productTypeDao.queryProductTypeByTypeId(rs.getInt("ptype"));
            product.setProductType(productType);
            product.setFileName(rs.getString("filename"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        super.closeAll();
    }
    return product;
}
 
Example 5
Project: iBase4J   File: InstanceUtil.java   View Source Code Vote up 6 votes
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
	List<E> resultList = newArrayList();
	try {
		E object = cls.newInstance();
		Field[] fields = cls.getDeclaredFields();
		while (rs.next()) {
			object = cls.newInstance();
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].getName();
				PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
			}
			resultList.add(object);
		}
	} catch (Exception e) {
		throw new InstanceException(e);
	}
	return resultList;
}
 
Example 6
Project: LOSY   File: DaoProyect.java   View Source Code Vote up 6 votes
public DefaultComboBoxModel getValue(){
    DefaultComboBoxModel modelo = new DefaultComboBoxModel();
    modelo.addElement("Selecciona Proyecto");
    String sql_select;
    sql_select="SELECT nombre_proyecto FROM  proyectos";// Where nombre_equipo LIKE '" + indi + "%'";
   
     try{
        Connection conn= fachada.getConnetion();
        System.out.println("consultando en la bd");
        Statement sentencia = conn.createStatement();
        ResultSet tabla = sentencia.executeQuery(sql_select);
        while(tabla.next()){
            modelo.addElement(tabla.getString(1));
        }
        tabla.close();
        sentencia.close();
      
     }
     catch(Exception e){ System.out.println(e);}
     return modelo;     
}
 
Example 7
Project: myqq   File: UserDao.java   View Source Code Vote up 6 votes
@Override
public boolean checkNameAndPwd(String name, String password)
{
	try
	{
		ResultSet rs = con.query("select * from users where u_name=? and u_pwd=? ",
				new String[] { name,password});
		if(rs.next())
			return true;
		else
			return false;
	}
	catch (Exception e)
	{
		e.printStackTrace();
		return false;
	}
}
 
Example 8
Project: bdf2   File: EntityPR.java   View Source Code Vote up 6 votes
private String getColumnRemarks(String tableName,String columnName,DatabaseMetaData databaseMetaData) throws SQLException{
	String remarks=null;
	ResultSet rs=null;
	try{
		rs=databaseMetaData.getColumns(null, null, tableName,"%");
		while(rs.next()){
			String colName=rs.getString("COLUMN_NAME");
			if(columnName.equals(colName)){
				remarks=rs.getString("REMARKS");
				break;
			}
		}
	}finally{
		if(rs!=null)rs.close();
	}
	return remarks;
}
 
Example 9
Project: AeroStory   File: MapleCharacter.java   View Source Code Vote up 6 votes
public int getPandoraLog(String itemid) {
Connection con1 = DatabaseConnection.getConnection();
try {
int ret_count = 0;
PreparedStatement ps;
ps = con1.prepareStatement("select count(*) from pandoralog where characterid = ? and itemid = ? and lastattempt >= subtime(current_timestamp, '1 0:0:0.0')");
ps.setInt(1, id);
ps.setString(2, itemid);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
ret_count = rs.getInt(1);
} else {
ret_count = -1;
}
rs.close();
ps.close();
return ret_count;
} catch (Exception Ex) {
	System.out.print("Error reading Pandora Log.");
return -1;
}
}
 
Example 10
Project: scorekeeperfrontend   File: SQLDataInterface.java   View Source Code Vote up 6 votes
@Override
public List<Integer> getUnavailableNumbers(UUID driverid, String classcode)
{
    List<Integer> ret = new ArrayList<Integer>();
    try
    {
        boolean superunique = Integer.parseInt(getSetting("superuniquenumbers")) != 0;
        ResultSet rs;

        if (superunique) {
            rs = executeSelect("select distinct number from cars where number not in (select number from cars where driverid=?)", newList(driverid));
        } else {
            rs = executeSelect("select distinct number from cars where classcode=? and number not in (select number from cars where classcode=? and driverid=?)", newList(classcode, classcode, driverid));
        }

        while (rs.next())
            ret.add(rs.getInt(1));
    }
    catch (Exception e)
    {
        logError("getUnavailableNumbers", e);
    }

    return ret;
}
 
Example 11
Project: SpringTutorial   File: MySQLUserDAO.java   View Source Code Vote up 6 votes
public void displayAllUsers() throws SQLException {

		ResultSet result = null;

		ps = conn
				.prepareStatement("select * from test.users");
		result = ps.executeQuery();

		int i = 0;
		while (result.next()) {
			System.out.println(++i + " -> " + result.getString(1) + " "
					+ result.getString(2) + " " + result.getString(3));
		}

		System.out.println("Select SQL executed successfully ");
	}
 
Example 12
Project: server   File: BlockHelper.java   View Source Code Vote up 6 votes
/**
 * Get block position in blockchain
 *
 * @param db data connection
 * @param id block id
 * @return block height or -1 if block not exist
 * @throws DataAccessException problems with the DB
 */
public static int getHeight(ConnectionProxy db, final long id) {
	try {

		PreparedStatement statement = db.prepareStatement("SELECT \"height\" FROM \"block\" where \"id\" = ?");
		int h = -1;
		synchronized (statement) {

			statement.setLong(1, id);

			ResultSet set = statement.executeQuery();
			while (set.next()) {
				h = set.getInt(1);
			}
			set.close();

		}

		return h;

	} catch (Exception e) {
		throw new DataAccessException(e);
	}
}
 
Example 13
Project: testcontainers-java-module-mariadb   File: SimpleMariaDBTest.java   View Source Code Vote up 5 votes
@NonNull
protected ResultSet performQuery(MariaDBContainer containerRule, String sql) throws SQLException {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(containerRule.getJdbcUrl());
    hikariConfig.setUsername(containerRule.getUsername());
    hikariConfig.setPassword(containerRule.getPassword());

    HikariDataSource ds = new HikariDataSource(hikariConfig);
    Statement statement = ds.getConnection().createStatement();
    statement.execute(sql);
    ResultSet resultSet = statement.getResultSet();

    resultSet.next();
    return resultSet;
}
 
Example 14
Project: ProyectoPacientes   File: BaseTestCase.java   View Source Code Vote up 5 votes
protected int getRowCount(String tableName) throws SQLException {
    ResultSet countRs = null;

    try {
        countRs = this.stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);

        countRs.next();

        return countRs.getInt(1);
    } finally {
        if (countRs != null) {
            countRs.close();
        }
    }
}
 
Example 15
Project: ProyectoPacientes   File: ResultSetRegressionTest.java   View Source Code Vote up 5 votes
/**
 * Tests that streaming result sets are registered correctly.
 * 
 * @throws Exception
 *             if any errors occur
 */
public void testClobberStreamingRS() throws Exception {
    try {
        Properties props = new Properties();
        props.setProperty("clobberStreamingResults", "true");

        Connection clobberConn = getConnectionWithProps(props);

        Statement clobberStmt = clobberConn.createStatement();

        clobberStmt.executeUpdate("DROP TABLE IF EXISTS StreamingClobber");
        clobberStmt.executeUpdate("CREATE TABLE StreamingClobber ( DUMMYID INTEGER NOT NULL, DUMMYNAME VARCHAR(32),PRIMARY KEY (DUMMYID) )");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (0, NULL)");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (1, 'nro 1')");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (2, 'nro 2')");
        clobberStmt.executeUpdate("INSERT INTO StreamingClobber (DUMMYID, DUMMYNAME) VALUES (3, 'nro 3')");

        Statement streamStmt = null;

        try {
            streamStmt = clobberConn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
            streamStmt.setFetchSize(Integer.MIN_VALUE);

            this.rs = streamStmt.executeQuery("SELECT DUMMYID, DUMMYNAME FROM StreamingClobber ORDER BY DUMMYID");

            this.rs.next();

            // This should proceed normally, after the driver clears the input stream
            ResultSet rs2 = clobberStmt.executeQuery("SHOW VARIABLES");
            rs2.next();
            this.rs.close();
        } finally {
            if (streamStmt != null) {
                streamStmt.close();
            }
        }
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS StreamingClobber");
    }
}
 
Example 16
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 5 votes
@Override
public void updateExpiryTime(Connection txn, ContactId c, MessageId m,
		int maxLatency) throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT txCount FROM statuses"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		ps.setInt(2, c.getInt());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbStateException();
		int txCount = rs.getInt(1);
		if (rs.next()) throw new DbStateException();
		rs.close();
		ps.close();
		sql = "UPDATE statuses SET expiry = ?, txCount = txCount + 1"
				+ " WHERE messageId = ? AND contactId = ?";
		ps = txn.prepareStatement(sql);
		long now = clock.currentTimeMillis();
		ps.setLong(1, calculateExpiry(now, maxLatency, txCount));
		ps.setBytes(2, m.getBytes());
		ps.setInt(3, c.getInt());
		int affected = ps.executeUpdate();
		if (affected != 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 17
Project: ace   File: TestH2.java   View Source Code Vote up 5 votes
public void testH2() {
    try {
        // 加载驱动
        Class.forName("org.h2.Driver");

        // 创建连接
        Connection conn = DriverManager.getConnection(sourceURL1, user, password);
        Statement stat = conn.createStatement();

        // 插入数据
        stat.execute("CREATE MEMORY Table If Not Exists t_person(id INT auto_increment PRIMARY KEY , name_1 VARCHAR ) ");
        stat.execute("delete from t_person");
        stat.execute("INSERT INTO t_person values (1,'abc')");
        // 查询数据
        ResultSet result = stat.executeQuery("select name_1 from t_person ");
        int i = 1;
        while (result.next()) {
            System.out.println(i++ + ":" + result.getString("name_1"));
        }

        result.close();
        stat.close();
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: L2jBrasil   File: SiegeGuardManager.java   View Source Code Vote up 4 votes
/**
 * Load guards.<BR><BR>
 */
private void loadSiegeGuard()
{
    Connection con = null;
    try
    {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement = con.prepareStatement("SELECT * FROM castle_siege_guards Where castleId = ? And isHired = ?");
        statement.setInt(1, getCastle().getCastleId());
        if (getCastle().getOwnerId() > 0)   // If castle is owned by a clan, then don't spawn default guards
            statement.setInt(2, 1);
        else
            statement.setInt(2, 0);
        ResultSet rs = statement.executeQuery();

        L2Spawn spawn1;
        L2NpcTemplate template1;

        while (rs.next())
        {
            template1 = NpcTable.getInstance().getTemplate(rs.getInt("npcId"));
            if (template1 != null)
            {
                spawn1 = new L2Spawn(template1);
                spawn1.setId(rs.getInt("id"));
                spawn1.setAmount(1);
                spawn1.setLocx(rs.getInt("x"));
                spawn1.setLocy(rs.getInt("y"));
                spawn1.setLocz(rs.getInt("z"));
                spawn1.setHeading(rs.getInt("heading"));
                spawn1.setRespawnDelay(rs.getInt("respawnDelay"));
                spawn1.setLocation(0);

                _siegeGuardSpawn.add(spawn1);
            }
            else
            {
                _log.warning("Missing npc data in npc table for id: " + rs.getInt("npcId"));
            }
        }
        statement.close();
    }
    catch (Exception e1)
    {
        _log.warning("Error loading siege guard for castle " + getCastle().getName() + ":" + e1);
    }
    finally
    {
        try { con.close(); } catch (Exception e) {}
    }
}
 
Example 19
Project: ts-benchmark   File: BizDBUtils.java   View Source Code Vote up 4 votes
/**
	 * 通过表名称,列名称插入数据
	 * @param columns
	 * @param values
	 * @param tableName
	 * @return
	 */
	public static long insertBySqlAndParamAndTable(String[] columns,Object[] values,String tableName){
		Connection conn=null;
		conn=getConnection();
		QueryRunner runner=new QueryRunner();
		ResultSetHandler<Integer> rsh=new ResultSetHandler<Integer>() {
			@Override
			public Integer handle(ResultSet rs) throws SQLException {
				while (rs.next()) {
					return rs.getInt(1);
				}
				return 1;
			}
		};
		long key=-1;
		try {
			StringBuilder sc=new StringBuilder();
			sc.append("insert into ");
			sc.append(tableName);
			sc.append("(");
			int columnSize=columns.length;
			for(int i=0;i<columnSize;i++){
				sc.append(columns[i]);
				if(i<columnSize-1){
					sc.append(",");
				}
			}
			sc.append(") values(");
			for(int i=0;i<columnSize;i++){
				sc.append("?");
				if(i<columnSize-1){
					sc.append(",");
				}
			}
			sc.append(")");
//			System.out.println("sql:"+sc.toString());
			runner.insert(conn, sc.toString(),rsh,values);
			String keySql="select last_insert_rowid() from "+tableName;
			key = (long) runner.query(conn, keySql, rsh);
		} catch (Exception e) {
			e.printStackTrace();
		}
		closeConnection(conn);
		return key;
	}
 
Example 20
Project: dev-courses   File: JDBCDatabaseMetaData.java   View Source Code Vote up 2 votes
/**
 * Retrieves whether this database is in read-only mode.
 *
 * <!-- start release-specific documentation -->
 * <div class="ReleaseSpecificDocumentation">
 * <h3>HSQLDB-Specific Information:</h3> <p>
 *
 * This makes an SQL call to the isReadOnlyDatabase function
 * which provides correct determination of the read-only status for
 * both local and remote database instances.
 * </div>
 * <!-- end release-specific documentation -->
 * @return <code>true</code> if so; <code>false</code> otherwise
 * @exception SQLException if a database access error occurs
 */
public boolean isReadOnly() throws SQLException {

    ResultSet rs = execute("CALL IS_READONLY_DATABASE()");

    rs.next();

    boolean result = rs.getBoolean(1);

    rs.close();

    return result;
}