Access 2003
VS 2010 C#
As subject title says I am having problems with. This is related to my previous question I asked, Here. I hope the mod's will be OK with this thread but I am not sure.
Martin Parkin advised not to close the connection between Insert and Select when using @@Identity
with C# and MS-Access. I thought I got it working until I discovered that was not the case. To be honest I don't know how to solve this issue. So if anyone can help me I would appreciate it.
This is my btnLogin method..
cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (@UserName, @LoggedInDate, @LoggedInTime)";
cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("@LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @ID = @@IDENTITY";
// cmd.Parameters.AddWithValue("@ID", OleDbType.WChar); << tried this, unsuccessful
int id = (int)cmd.ExecuteScalar(); // getting the same error?
myCon.Close();
This is my btnLogOut method...
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
int id = 0;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = @LoggedOutDate, [LoggedOutTime] = @LoggedOutTime WHERE [ID] = @ID";
cmd.Parameters.AddWithValue("@ID", id);
cmd.Parameters.AddWithValue("@LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
Close();
Or
In the btnLogin
method if I do
cmd.CommandText = "SELECT @ID = @@IDENTITY";
and hide the cmd.ExecuteNonQuery();
after it. Then date and time will get logged in the database but the date and time will not get saved in the database, for logging out.
I am not sure if the problem is with btnLogin
method or btnLogOut
method, or both.
Working Solution
Originally I did
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = @LoggedOutDate,
[LoggedOutTime] = @LoggedOutTime WHERE [ID] = @ID";
cmd.Parameters.AddWithValue("@ID", id);
cmd.Parameters.AddWithValue("@LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@LoggedOutTime", DateTime.Now.ToString("HH:mm"));
Then I did this
cmd.CommandText = " UPDATE [LoginLogTable] SET [UserName] = @UserName, [LoggedOutDate] =
@LoggedOutDate, [LoggedOutTime] = @LoggedOutTime WHERE ID = @ID";
cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("@LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Parameters.AddWithValue("@ID", id);
Thanks to D Stanley and Gord Thompson.