Is it possible in C# / ASP.NET to know if the ExecuteNonQuery inserted a record or not?

I am checking to make sure the email address does not exist in the table using a subquery.

Is there a way to know if an Insert was made in ASP.NET?

CommandPrizeEmails.Parameters.Add("@Email", SqlDbType.VarChar, 50);
CommandPrizeEmails.Parameters.Add("@DateToday", SqlDbType.DateTime);

CommandPrizeEmails.Parameters["@Email"].Value = txtEmail.Text;
CommandPrizeEmails.Parameters["@DateToday"].Value = DateTime.Now;

CommandPrizeEmails.ExecuteNonQuery();

//int newID = (int)CommandPrizeEmails.ExecuteScalar();

//CommandPrizeEmails.ExecuteNonQuery();
//if (newID >= 1) {
//    divSuccesfulEntry.Visible = true;
//} else {
//    divRepeatEntry.Visible = true;
//}
有帮助吗?

解决方案

You can get the rows affected in return to verify the process.

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.

When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of

rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

http://blogs.msdn.com/b/spike/archive/2009/01/27/sqlcommand-executenonquery-returns-1-when-doing-insert-update-delete.aspx

其他提示

ExecuteNonQuery Return Boolean value catch value

ex:

bool flg;

flg=cmd.ExecuteNonQuery(); 
if (flg)
{ msgbox("successfully inserted");}
else {msgbox("not inserted");}
bool flg;

flg=cmd.ExecuteNonQuery(); 
if (flg)
{ MessageBox.Show("successfully inserted");
}
else 
{
MessageBox.Show("not inserted");
}

This gives an error as:

Can not implicitly convert type 'int' to 'bool'

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top