0

I have two questions for java mysql

First, I have an array containing either 1 or 0.

If i want do to an if statement how can i then check if opt[0] = 1? is it like:

if (options[0] == 1
{
sqlBuilder.append("AND a.value1 = val[1]")
}

next question. I have another array containing different values, how can i use them in a mysql query.

Right now i got

StringBuilder sqlBuilder = new StringBuilder()
.append("SELECT * ")
.append("FROM `table1` a ")
.append("CROSS JOIN `table2` b ")
.append("CROSS JOIN ` table3` c ")
.append("CROSS JOIN `table4` d")
.append("WHERE c.`id` =" . val[0] );

So i need c.id = val[0]

6
  • For the first question; yes that looks fine aside from the missing ) after the ==1. Assuming that options[] is an int[]. Commented Jun 27, 2014 at 10:21
  • 2
    @Mister: No, he is missing a closing parenthesis, lol. Same for the second example, just replace . by + and you are fine. Commented Jun 27, 2014 at 10:22
  • true i miss a closing. But when i wrte if (options[0] == 1) i get the error operand strings and int.. options is a string[] Commented Jun 27, 2014 at 10:24
  • 2
    Shouldn't "AND a.value1 = val[1]" actually be "AND a.value1 = '" + val[1] + "'"? And btw, this is quite vulnerable to SQL injection so please use PreparedStatements instead. Commented Jun 27, 2014 at 10:26
  • @KlausJoeChristiansen: See my answer, you cannot compare int with String; this is neither PHP nor Javascript. Commented Jun 27, 2014 at 10:26

1 Answer 1

2

Basically, your code is correct.

The thing that is incorrect is your Java syntax. Are you coming from PHP? Strings are concatenated with + in Java, so your last line should be

.append("WHERE c.`id` =" + val[0] );

In addition, you seem to mess up types; if your option array is a String[] then you need to compare it with strings or cast the value to int, so your first if must look like this:

if("1".equals(options[0]))

or

if(Integer.parseInt(options[0]) == 1)

Note:

As Thomas correctly states in his comment, you should consider using PreparedStatments instead of your hardcoded statements to avoid SQL injection attacks.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes i am coming from PHP. I will definetly look into prepared statements. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.