2016-11-12 74 views
0

我想使用date函數更新數據庫中的date_n,但它總是給我一個錯誤'unclosed character literal'。使用迄今爲止的函數在jdbc中更新Date_n

try { 
    // TODO add your handling code here: 
    String radio = ""; 
    String date = f.format(jDateChooser1.getDate()); 
    if(jRadioButton1.isSelected()){ 
     radio ="Masculin"; 
    }else{ 
     if(jRadioButton2.isSelected()){ 
      radio ="Féminin"; 
     } 
    } 
    requete =" update humain set nom = '"+jTextField2.getText()+"',prenom='"+jTextField3.getText()+"',adresse ='"+jTextField4.getText()+"',date_n="'to_date('"+date+"','yyyy-mm-dd')"+"',sex = '"+radio+"'where id= '"+jTextField1.getText()+"'"; 
    state.executeUpdate(requete); 
    RefreshTable(); 
} catch (SQLException ex) { 
    Logger.getLogger(easy_methodes.class.getName()).log(Level.SEVERE, null, ex); 
} 

回答

1

爲了避免sql字符串連接錯誤和跨站腳本問題(看here),您需要使用preparedstatement.setString()setDate()等。如下圖所示:

SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd"); 
java.sql.Date sqlDate = new java.sql.Date(jDateChooser1.getDate().getTime()); 

requete = "update humain set nom = ?, prenom=?, adresse=?, date_n=?, sex=? where id=?"; 
state = con.prepareStatement(requete); 
updateSales.setString(1, jTextField2.getText()); 
updateSales.setString(2, jTextField3.getText()); 
updateSales.setString(3, jTextField4.getText()); 
updateSales.setDate(4, sqlDate); 
updateSales.setString(5, radio); 
updateSales.setString(6, jTextField1.getText()); 
state.executeUpdate(requete); 
+0

我在日起使用Jdatechooser至極,我添加像這樣的格式(「yyyy-MM-dd」)jDateChooser1.setDateFormatString(「yyyy-MM-dd」); –

+0

已更新的答案從jDateChooser1.getDate()獲取sqldate – developer