Reputation: 1073
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);
}
Upvotes: 0
Views: 244
Reputation: 1073
Finally I got it !!!
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);
}
Upvotes: 1
Reputation: 2641
What you should be doing is to add another foreign key for user (make it primary as well) to the date-logs
table. Even if you insert the same data twice it will ignore the query since the primary key already exists in the database.
Upvotes: 0
Reputation: 12306
I don't know which database abstraction stuff you're using, but you should update it to use prepared statements.
Next, you should use MySQL specific query, like:
insert into date logs ... on duplicate key ignore
make sure that Date is primary key. This kind of query will ignore inserts if the key already exists in the database.
Upvotes: 0