如何知道sql Update语句是成功执行还是失败?
我使用sql server 2005和C#asp.net.
我是否可以在C#中获取成功或失败的信息,而无需在旧的sql语句中添加一些sql代码?
Dea*_*ing 11
您可以使用@@ ROWCOUNT来获取上次查询所影响的行数.例如,这可用于确定您的WHERE子句是否实际匹配某些内容.
UPDATE mytable SET
field = 'SomeValue'
WHERE
id = 1234
IF @@ROWCOUNT = 0
BEGIN
-- No row with id=1234
END
Run Code Online (Sandbox Code Playgroud)
Chi*_*joo 11
您可以使用ExecuteNonQuery的返回值来检查更新是否成功.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_updateData", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("@id", SqlDbType.Int);
p1.Value = 1;
p1.Direction = ParameterDirection.Input;
SqlParameter p2 = new SqlParameter("@name", SqlDbType.VarChar,50);
p2.Value = "sls";
p2.Direction = ParameterDirection.Input;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
try
{
con.Open();
//count will be the number of rows updated. will be zero if no rows updated.
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Console.WriteLine("Update Success!!!");
}
else
{
Console.WriteLine("No Updates!!!");
}
Console.ReadLine();
}
catch (SqlException ex)
{
Console.WriteLine("Update Failed coz.. " + ex.Message);
}
finally
{
con.Close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37289 次 |
| 最近记录: |