0

I am saving date logs every time a user logs in. Date logs will save a date in the record, but what I want is for there to be no duplicates. It will check if the record is already existing, and if yes it will not save the date. If the record does not yet exist it will save the date.

Here is my code:

 SimpleDateFormat dnow2 = new SimpleDateFormat("MMMMM dd, yyyy");

 ResultSet ds = MyDB.rsFetch("SELECT * FROM `date-logs` WHERE `Date` = '"+dnow.format(new java.util.Date())+"'");

 try {
   ds.next() ; 

   if (ds.getMetaData().getColumnCount() == 0) {
     MyDB.exSQL(  "INSERT INTO `date-logs` (`Date Code`, `Date`) " 
                + "VALUES ('"+dnow.format(new java.util.Date())+ "',"
                + "'"+dnow2.format(new java.util.Date())+"')");   
   }
 } catch (SQLException ex) {
   Logger.getLogger(FrmLogIn.class.getName()).log(Level.SEVERE, null, ex);
 }
4

3 回答 3

1

最后我得到了它 !!!

 SimpleDateFormat dnow2 = new SimpleDateFormat("MMMMM dd, yyyy");

    ResultSet ds = MyDB.rsFetch("SELECT * FROM `date-logs` WHERE `Date Code` = '"+dnow.format(new java.util.Date())+"'");


  int resultsCounter = 0;  
    try {
        while(ds.next())  
        {  
        //procedure when results were returned  
        resultsCounter++;  
        }

        if (resultsCounter ==0)  
        {  

      MyDB.exSQL("INSERT INTO `date-logs` (`Date Code`, `Date`) VALUES ('"+dnow.format(new java.util.Date())+ "',"
                     + "'"+dnow2.format(new java.util.Date())+"')");
        }  
    } catch (SQLException ex) {
        Logger.getLogger(FrmLogIn.class.getName()).log(Level.SEVERE, null, ex);
    }
于 2013-02-21T03:37:35.250 回答
0

您应该做的是将用户的另一个外键(也将其设为主键)添加到date-logs表中。即使您两次插入相同的数据,它也会忽略查询,因为主键已经存在于数据库中。

于 2013-02-21T02:46:07.137 回答
0

我不知道您使用的是哪种数据库抽象,但您应该更新它以使用准备好的语句

接下来,您应该使用 MySQL 特定查询,例如:

insert into date logs ... on duplicate key ignore 

确保 Date 是主键。如果该键已存在于数据库中,这种查询将忽略插入。

于 2013-02-21T01:12:20.400 回答