C# 执行时出现意外的无法准备错误
出于测试目的,我有以下代码存在故意语法错误C# 执行时出现意外的无法准备错误,c#,sql-server,C#,Sql Server,出于测试目的,我有以下代码存在故意语法错误 const string sql = @" INSERT RUNHISTORY ( r_activity_id) (@r_activity_id) -- Intentional missing VALUES "; SqlCommand command = new SqlCommand(sql, connection); command.Parameters.Add(new SqlParam
const string sql = @"
INSERT RUNHISTORY ( r_activity_id)
(@r_activity_id) -- Intentional missing VALUES
";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add(new SqlParameter("@r_activity_id", System.Data.SqlDbType.Int, 0));
command.Prepare();
command.Parameters[0].Value = r_activity_id;
int rowsUpdated = command.ExecuteNonQuery(); // This line throws exception.
我得到:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '@r_activity_id'.
Statement(s) could not be prepared.
我希望在Prepare()
行而不是Execute()
行中得到该错误
这对我来说很重要,因为我在程序执行的早期准备了所有sql,以便在程序执行任何有意义的操作之前发现问题并停止
如何在
Prepare()
语句中捕获此错误。该方法似乎不再引发异常:
在VisualStudio2010之前,Prepare引发了一个异常。始于
VisualStudio2010,此方法不会引发异常