0
0

More than 1 year has passed since last update.

JavaでPostgreSQLのエラーコードを取得する

Posted at

PostgreSQLには、エラーの種類に応じてエラーコードがある。
詳細は公式ページを参照。
数えてみたら199種類あった。
とはいってもお目にかかるのはほぼ「23 クラス — 整合性制約違反」だとは思う。

このエラーコードをMyBatisでクエリ実行したときに取得したい。
※試してはいないが、別にMyBatisでなくてSpring JDBCやJPAなど他のデータベースマッパー、ORマッパーであっても同じようにできるはず。

catch節をこのようにする。

}catch(Exception e){
    String errorCode = ((SQLException)e.getCause()).getSQLState();
    System.out.println(errorCode);
}

MyBatisでの一例

Articles articles = new Articles(){{
    setArticleTitle("タイトル");
}};

try{
    articlesMapper.insertSelective(articles);
}catch(Exception e){
    String errorCode = ((SQLException)e.getCause()).getSQLState();
    System.out.println(errorCode);
}

非NULL違反の場合、23502がerrorCodeとして取得できた。

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