Hack Forums
[Java] SQL in Java, check if value in table column is NULL - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Java] SQL in Java, check if value in table column is NULL (/showthread.php?tid=4856499)



SQL in Java, check if value in table column is NULL - Vanilja - Jun 8, 2015

Hi.
So let's take this table for example, we call it Messages
[Image: ab0253305a04481ed9d3806ccfaa51bc.png]

By default, receiver value is always NULL.
I am trying to display all Messages where receiver is NULL.
But how?

Since this wont work.
Code
System.out.println("1. Read messages 2. Send message 0. Quit");
            answer=reader.nextInt();
            reader.nextLine();
            if(answer==1)
            {
                try{
                    st = con.createStatement();
                    rs = st.executeQuery("SELECT Message FROM Messages WHERE Receiver = IS NULL");
                    while (rs.next()) {
                        System.out.println(rs.getString(1));
                    }
                }catch(SQLException ex){
                    System.out.println(ex.toString());

This is the error message
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IS NULL' at line 1


* - Kain_12 - Jun 8, 2015

You should type Receiver = NULL, not Receiver = IS NULL. That is the mistake.


* - Vanilja - Jun 8, 2015

(Jun 8, 2015 03:01 PM)Kain_12 Wrote:  You should type Receiver = NULL, not Receiver = IS NULL. That is the mistake.
Tried it, does not display anything. That's the problem.

Just wondering, does it matter what type it is? It is int right now, but it should not matter since it's NULL by default right?

[Image: b0d566b8288ebf1a5714983ca99e8011.png]

E: Working now, it had to be RECEIVER IS NULL, just had to remove the =.


* - nOrr - Jun 8, 2015

(Jun 8, 2015 03:01 PM)Kain_12 Wrote:  You should type Receiver = NULL, not Receiver = IS NULL. That is the mistake.

No it's not.

(Jun 8, 2015 03:04 PM)HOLLi Wrote:  E: Working now, it had to be RECEIVER IS NULL, just had to remove the =.

There we go.

Alternatively, the notation <> usually works, too. That means "is different from", e.g. WHERE USER_ID <> 42.