if/else not working properly.

[nobr]Hi All,

I'm using an if/else statement to avoid outputting duplicating headings from my database.

Basically im trying to make a master brand list along with all products under said brand. But because of the way i have my DB set-up, whenever i loop through all the products and brands, it says the brand name each and every time. I only want to display the brand name once instead of each time that brand/product come up. I don't know if that makes 100% sense.

Here's a bit of a visual of what i mean.

This is what happens. I do not want this.

Hot Wheels car1

Hot Wheels car2

Hot Wheels car3

Barbie doll1

Barbie doll2

Barbie doll3

What i want this to look like is this.

Hot Wheels

Car1

Car2

Car3

Barbie

doll1

doll2

doll3

Here is all the code.

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>

<%!

// define variables

String x_ID;

String x_productName;

String x_brandName;

String oldBrand;

// define database parameters

String host="localhost";

String user="root";

String pass="password";

String db="datab";

String conn;

%>

<%

Class.forName("org.gjt.mm.mysql.Driver");

// create connection string

conn ="jdbc:mysql://" + host +"/" + db +"?user=" + user

+"&password=" + pass;

// pass database parameters to JDBC driver

Connection Conn = DriverManager.getConnection(conn);

// query statement

Statement SQLStatement = Conn.createStatement();

// generate query

String Query ="SELECT ID, brandName, productName FROM datab.uk";

// get result

ResultSet SQLResult = SQLStatement.executeQuery(Query);

while(SQLResult.next())

{

x_ID = SQLResult.getString("ID");

x_productName = SQLResult.getString("productName");

x_brandName = SQLResult.getString("brandName");

if(oldBrand != x_brandName){

out.print(x_brandName);

out.print(x_productName);

out.print(oldBrand);

}else{

out.print(x_productName);

}

%>

<br/>

<% oldBrand = SQLResult.getString("brandName"); %>

<BR />

<%

}

SQLResult.close();

SQLStatement.close();

Conn.close();

%>

For some reason my != doesn't work properly with values from the database.If i define two seperate variable Strings with the same value- it works. I don't know why it works that way, but refuses to work the way i have it setup above.

Anyone?[/nobr]

[3705 byte] By [iggy_popa] at [2007-10-2 14:31:18]
# 1

It's not a good idea to compare objects (including Strings) using == and !=. Instead, use:

if (!(x_brandName.equals(oldBrand) )

Also, after you have alread called rs.getString("brandName") you call it a second time to give the results to oldBrand. This is also a bad idea. You already have the value, just use:

<% oldBrand = x_brandName; %>

instead.

stevejlukea at 2007-7-13 12:53:28 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...