我是应用程序块的新手。
我正在尝试在数据库中插入数据。以下是代码捕捉。
private int Id;
private string Title;
private string Description;
private DateTime Start;
private DateTime End;
private int User_id;
public int id
{
get
{
return Id;
}
set
{
Id = value;
}
}
public string title
{
get
{
return Title;
}
set
{
Title = value;
}
}
public string description
{
get
{
return Description;
}
set
{
Description = value;
}
}
public DateTime start
{
get
{
return Start;
}
set
{
Start = value;
}
}
public DateTime end
{
get
{
return End;
}
set
{
End = value;
}
}
public int user_id
{
get
{
return User_id;
}
set
{
User_id = value;
}
}
public static int addEvent(CalendarEvent cevent)
{
try
{
SqlParameter[] sqlParam = new SqlParameter[5];
sqlParam[0] = new SqlParameter("@title", cevent.title);
sqlParam[0].Direction = ParameterDirection.Input;
sqlParam[1] = new SqlParameter("@description", cevent.description);
sqlParam[1].Direction = ParameterDirection.Input;
sqlParam[2] = new SqlParameter("@event_start", Convert.ToString(cevent.start));
sqlParam[2].Direction = ParameterDirection.Input;
sqlParam[3] = new SqlParameter("@event_end", Convert.ToString(cevent.end));
sqlParam[3].Direction = ParameterDirection.Input;
sqlParam[4] = new SqlParameter("@user_id", cevent.user_id);
sqlParam[4].Direction = ParameterDirection.Input;
return Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, "SaveData", sqlParam));
}
catch
{
throw;
}
SQLHelper类:
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);
//execute the command & return the results
object retval = cmd.ExecuteScalar();
// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}
我在对象retval = cmd.ExecuteScalar()
中收到错误无法将参数值从SqlParameter转换为字符串。我无法理解问题所在。
答案 0 :(得分:1)
SQLHelper.ExecuteScalar
方法的函数签名是
ExecuteScalar(SqlConnection, CommandType, string, params SqlParameter[])
你正在使用
SqlHelper.ExecuteScalar(connectionString, "SaveData", sqlParam)
你必须通过CommandType
,你没有在函数调用中传递CommandType
使用
SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, "SaveData", sqlParam)
根据您的要求传递CommandType
此外,我认为你需要通过SqlConnection
,所以使用
SqlHelper.ExecuteScalar(new SqlConnection(connectionString), CommandType.StoredProcedure, "SaveData", sqlParam)