0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MySQLでDATETIME 型にnullを挿入する方法

Posted at

今回、返却日:DATETIME 型に空文字が自動で挿入され、登録ができないということがありました。

nullは登録することは可能でした。(workbenchで直接、値を入力して)

空文字をnullに変更する方法を書いていきたいとと思います。

空文字をnullに変更(例)

前提
HashMapクラス(連想配列)に空文字が入っています。
その空文字をnullに変換して出力します。

package sa;

import java.util.HashMap;

public class Main {

	public static void main(String[] args) {

		//型引数を指定してHashMapクラスのオブジェクトを生成
		//Map<データ型, データ型> マップ変数 = new HashMap<データ型, データ型>();
		 HashMap<String, Object> resultMap = new HashMap<String, Object>();

		 //値を追加  map.put(キー名, 値);
		 resultMap.put("返却日", "2019-10-04 15:25:07");
		 resultMap.put("返却日1", "");//値は空文字

		 try {
			 if(resultMap.get("返却日").equals("")) {
			      System.out.println("空文字です");//返却日の値が空文字だった場合
			    }else {
				      System.out.println(resultMap.get("返却日"));//それ以外は返却日の値を表示

			    }
	        } catch(NullPointerException e) {
			      System.out.println("nullです");
	        }

		 if(resultMap.get("返却日1").equals("")) {
			 resultMap.put("返却日1",null);//値にnull代入
		    }

		 try {
			 if(resultMap.get("返却日1").equals("")) {
			      System.out.println("空文字です");
			    }else {
				      System.out.println(resultMap.get("返却日1"));

			    }
	        } catch(NullPointerException e) {
	        	//NullPointerExceptionは参照型変数にnull値が格納されている時に、参照型変数を参照しようとした場合に発生する例外
	        	//返却日1の値はnullのため「返却日1の値はnullです」が表示される
			      System.out.println("返却日1の値はnullです");

	        }

	}
}
2019-10-04 15:25:07    //返却日
返却日1の値はnullです  //返却日1

返却日1は元々空文字だったのですが、nullを代入することができました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?