How do I insert a NULL long value?

17,803

Solution 1

If you desperately need to use numerics for the phone number, why not just code a non-existing phone number into something like 0L or -1L?

Edit: Btw, you say that the database is limited to numeric format. Does the same go for the java side?

long dbPhoneNumber = getTheLongFieldFromTheDatabase();
String internalPhoneNumberRepresentation = Long.toString(dbPhoneNumber);
doSomethingWithString();
dbPhoneNumber = internalPhoneNumberRepresentation == null ? 0L : internalPhoneNumberRepresentation;
storeLongFieldToDatabase(dbPhoneNumber);

Should more or less do all you need, right?

Solution 2

Because the phone number is 10 digits, in my code I have captured the variable as a LONG.

Bad idea. Phone numbers might look like numbers, but they're not. They're strings of characters that happen to be mostly digits. But they can also contain symbols such as +.

Use a String instead.


Update: If you are required to use a numeric type then make sure you use Long instead of long. The capitilazation is important. And by the way, there is no such type as LONG in standard Java.

Share:
17,803
Jay Lefler
Author by

Jay Lefler

I'm a college student with a love for technology and programming.

Updated on August 01, 2022

Comments

  • Jay Lefler
    Jay Lefler almost 2 years

    I have a database made up a single table with several fields, one of which is a phone number that is stored as a NUMERIC. Because the phone number is 10 digits, in my code I have captured the variable as a LONG.

    My question is, in the insert statement, how do I pass a NULL value? Is this possible at all? I can't assign a null value to the LONG variable, so I'm wondering how to go about doing this...

    • Eng.Fouad
      Eng.Fouad over 12 years
      Long can take null, but long cannot.
    • Etienne de Martel
      Etienne de Martel over 12 years
      Using a numeric field for a phone number has always struck me as odd.
    • Grambot
      Grambot over 12 years
      If you want to insert a value to a LONG field that is easily recognizable as blank or incorrect use 0. You can check against that if you need. But as Eng.Fouad said you can't assign null to a primitive type (long) but you can to an object (Long).
    • Jay Lefler
      Jay Lefler over 12 years
      Passing Long value with null to the database results in the program crashing.
  • JB Nizet
    JB Nizet over 12 years
    Yes, or simply start with a 0 (that's the case of all the phone numbers where I live)
  • Jay Lefler
    Jay Lefler over 12 years
    I can't use string. The software specifications require the database value be numeric.
  • Clockwork-Muse
    Clockwork-Muse over 12 years
    Phone numbers can also be up to 15 digits, not 10 (when dealing with international numbers, which is also where + comes into play).