Hello,
I'm a fairly new programmer and trying to get some code working, that just doesn't want to work so came for some advice. Basically I'm having this search for a specific user_id. If it exists it should update the row. If it doesn't exist it should insert a new row with the appropriate data.
It appears to work for creating new rows. However, it never updates even if the row is there. I tested the update lines of code by itself and they work. So I'm doing something incorrectly. Take a look at the code below:
Any help would be much appreciated.
I'm a fairly new programmer and trying to get some code working, that just doesn't want to work so came for some advice. Basically I'm having this search for a specific user_id. If it exists it should update the row. If it doesn't exist it should insert a new row with the appropriate data.
It appears to work for creating new rows. However, it never updates even if the row is there. I tested the update lines of code by itself and they work. So I'm doing something incorrectly. Take a look at the code below:
Code:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM users WHERE user_id=?");
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("user_id", userIDHiddenField.Value.ToString());
using (OleDbDataReader Reader = cmd.ExecuteReader())
{
if (Reader.HasRows)
{
Reader.Close();
cmd.CommandText = @"UPDATE users SET user_first_name = @user_first_name, " +
"user_last_name = @user_last_name, user_email = @user_email " +
"WHERE user_id = @user_id";
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@user_first_name", userFirstNameTextBox.Text);
cmd.Parameters.AddWithValue("@user_last_name", userLastNameTextBox.Text);
cmd.Parameters.AddWithValue("@user_email", userEMailTextBox.Text);
cmd.Parameters.AddWithValue("@user_id", userIDHiddenField.Value.ToString());
cmd.ExecuteNonQuery();
}
else
{
Reader.Close();
cmd.CommandText = @"INSERT INTO users (user_id, user_first_name, user_last_name, user_email) " +
"VALUES (@user_id, @user_first_name, @user_last_name, @user_email)";
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@user_first_name", userFirstNameTextBox.Text);
cmd.Parameters.AddWithValue("@user_last_name", userLastNameTextBox.Text);
cmd.Parameters.AddWithValue("@user_email", userEMailTextBox.Text);
cmd.Parameters.AddWithValue("@user_id", userIDHiddenField.Value.ToString());
cmd.ExecuteNonQuery();
}
}