C#带参数的存储过程 [英] C# stored procedure with parameters
本文介绍了C#带参数的存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的应用程序中收到一个错误,我不知道如何解决它.代码如下:
I am receiving an error in my application and i can not figure out how to resolve it. Here is the code:
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
myConnection.Open();
SqlCommand cmd = new SqlCommand("SELECT ServerIP FROM Servers", myConnection);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
string serverIP = rdr["ServerIP"].ToString();
ScheduledTasks st = new ScheduledTasks(@"\" + serverIP);
string[] taskNames = st.GetTaskNames();
foreach (string name in taskNames)
{
Task t = st.OpenTask(name);
var status = t.Status;
var recentRun = t.MostRecentRunTime;
var nextRun = t.NextRunTime;
var appName = t.ApplicationName;
SqlConnection myConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
SqlCommand myCommand2 = new SqlCommand("sp_AddScheduledTasks", myConnection2);
try
{
myConnection2.Open();
myCommand2.CommandType = CommandType.StoredProcedure;
myCommand2.Parameters.Add("@ID", SqlDbType.Int);
myCommand2.Parameters["@ID"].Direction = ParameterDirection.Output;
myCommand2.Parameters.Add("@ServerIP", SqlDbType.NVarChar, 20).Value = serverIP;
myCommand2.Parameters.Add("@TaskName", SqlDbType.NVarChar, 50).Value = t;
myCommand2.Parameters.Add("@MostRecentRun", SqlDbType.DateTime).Value = recentRun;
myCommand2.Parameters.Add("@NextRunTime", SqlDbType.DateTime).Value = nextRun;
myCommand2.Parameters.Add("@AppName", SqlDbType.NVarChar, 50).Value = appName;
myCommand2.Parameters.Add("@Status", SqlDbType.NVarChar, 50).Value = status;
int rows = myCommand2.ExecuteNonQuery();
}
finally
{
myConnection2.Close();
}
我收到的错误是 ExecuteNonQuery
.它说
The error I am receiving is with the ExecuteNonQuery
. It says
InvalidCastException 失败将参数值从任务转换为一个字符串.
InvalidCastException Failed to convert parameter value from a Task to a String.
我认为这与我放置 try(在 if 语句中)的位置有关,但我不确定.任何帮助将不胜感激.
I thought it had something to do with where I put the try (inside the if statement) but I am not sure. Any help would be much appreciated.
谢谢,
马特
推荐答案
我的猜测是在
myCommand2.Parameters.Add("@TaskName", SqlDbType.NVarChar, 50).Value = t;
t 不是字符串?
这篇关于C#带参数的存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文