2016-07-27 4 views
1

私の主なキーはempiddateです。私がしたいのは、従業員がSQL Serverに値を挿入し、同じ日に値をデータベースに挿入しようとした場合、主キーが競合するはずです。私は、彼/彼女は私はあなたのデータベーステーブルのdat日付列に一意制約を追加することによって、これについて行くだろうというどのようにsqlserverから私のJavaプログラマーにエラーメッセージを取得できます

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
      String g = jComboBox1.getSelectedItem().toString(); 
      if(g.equals("--Select Your Employee ID--")) 
      { 
      jLabel6.setForeground(Color.RED); 
      jLabel6.setText("Please Select Your ID "); 
      } 
      else{ 
       jLabel6.setText(""); 
      } 
      String a =jTextArea1.getText(); 
      if(a.equals("")){ 
       jLabel7.setForeground(Color.RED); 
      jLabel7.setText("Please Fill the Report "); 
      } 
      else{ 
       jLabel7.setText(""); 
      } 
       try{ 
      String url="jdbc:sqlserver://localhost:1433;databaseName=gym2 "; 
       String username = "mali"; 
       String password = "12345"; 
       Connection con =DriverManager.getConnection(url,username,password); 
       Statement st = con.createStatement(); 
       ResultSet rs; 
         Calendar cal = Calendar.getInstance(); 
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); 
     String sql = "INSERT INTO report(empid,dat,rep) VALUES('"+g+"','"+format1.format(cal.getTime())+"','"+a+"')" ; 
     rs= st.executeQuery(sql); 
     jComboBox1.addItem("--Select Your Employee ID--"); 

      } 
      catch(Exception e){ 

      } 

答えて

0

好きですしようとすると、エラーを表示したいです。その後、SQL Serverは制約違反になるため、同じ日付を含む挿入を拒否する必要があります。

理想的には、SQL Server JDBCドライバはこの場合例外をスローします。

try { 
    // attempt the INSERT 
} 
catch (SQLIntegrityConstraintViolationException e) { 
    System.out.println("date has already been entered"); 
} 
catch (SQLException e) { 
    // handle other SQL exceptions here 
} 
catch (Exception e) { 
    // handle generic exceptions here 
} 
+0

私はそれをlableに得ることができますか?役に立たなかった –

+0

あなたのコメントが分かりません。 –

+0

jframeでjlableに結果を得ることができません –

0

優しい方法:もしそうなら、あなたはこのような何かを見て、あなたのtry-catch句を変更することができ は、レコードの選択を行うと、レコードが存在するかどうかを確認します。ユーザーレコードが既に存在することを伝えます。

重複キーは制約に違反し、エラーが発生し、例外がアプリケーションに渡されます。

関連する問題