2016-07-27 19 views
1

我的主鍵是empiddate。我想要做的是員工向sql server插入值,如果他再次嘗試在同一天向數據庫插入值,那麼主鍵應該是衝突的。所以我想,如果他/她試圖做這樣的我如何從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

我會去這個在你的數據庫表中增加對dat日期列的唯一約束,以顯示錯誤。然後,SQL Server應該拒絕包含相同日期的任何插入,因爲它會違反約束。

理想情況下,在這種情況下,SQL Server JDBC驅動程序會引發異常。如果是這樣,那麼你可以修改你的try-catch子句是這個樣子:

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

我可以得到它的標籤?不工作 –

+0

我不明白你的評論。 –

+0

它不工作我想在jframe中得到一個jable的結果 –

0

友好的方式: 做一個選擇的記錄,並檢查是否存在記錄。告訴用戶記錄已經存在。

由於它是一個主鍵重複將違反約束和錯誤將引發異常將傳遞到應用程序。

相關問題