有人可以告诉我为什么我得到以下错误,当我通过我的代码,我不确定它是否与我的SQL语句的问题,因为这似乎是好的,但我在下面添加它,以便我可以得到一个第二个意见
"从字符串转换日期/时间时转换失败"
public static int GetConveyorProductionCount(string machineNameV, string StartTimeV, string EndTimeV)
{
try
{
int count;
SqlParameter param01 = new SqlParameter("@param01", SqlDbType.VarChar, 5);
param01.Value = machineNameV;
SqlParameter param02 = new SqlParameter("@param02", SqlDbType.VarChar, 5);
param02.Value = StartTimeV;
SqlParameter param03 = new SqlParameter("@param03", SqlDbType.VarChar, 5);
param03.Value = EndTimeV;
SqlCommand getConveyorProductionSC = new SqlCommand("SELECT cast([" + machineNameV + "] as int) FROM VWCONVEYORPRODUCTION WHERE([DA_TE] BETWEEN @param02 AND @param03)", myConnection);
getConveyorProductionSC.Parameters.Add(param01);
getConveyorProductionSC.Parameters.Add(param02);
getConveyorProductionSC.Parameters.Add(param03);
myConnection.Open();
object result = getConveyorProductionSC.ExecuteScalar();
myConnection.Close();
if (result == DBNull.Value)
{
count = 0;
}
else
{
count = Convert.ToInt32(result);
}
return count;
}
catch (Exception e)
{
throw new Exception("Error retrieving the Conveyor production count. Error: " + e.Message);
}
Run Code Online (Sandbox Code Playgroud)
除了这段代码的大量其他问题
SqlParameter param02 = new SqlParameter("@param02", SqlDbType.DateTime);
param02.Value = StartTimeV;
SqlParameter param03 = new SqlParameter("@param03", SqlDbType.DateTime);
param03.Value = EndTimeV;
Run Code Online (Sandbox Code Playgroud)
这将是一个好的开始假设当然表中的DA_TE列是一个日期时间?当然,您还需要将它们作为DateTimes传递
我确实赞扬你使用参数化查询.
如果是我,我的代码看起来像
public static int GetConveyorProductionCount(string machineNameV, DateTime StartTimeV, DateTime EndTimeV)
{
{
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.Open();
using(SqlCommand command = new SqlCommand(String.Format(CultureInfo.InvariantCulture, "SELECT cast([{0}] as int) FROM VWCONVEYORPRODUCTION WHERE([DA_TE] BETWEEN @StartDate AND @EndDate)", machineNameV), connection);
{
command.Parameters.AddWithValue("StartDate",StartTimeV);
command.Parameters.AddWithValue("EndDate",EndTimeV);
object result = command.ExecuteScalar();
if (result == DBNull.Value)
{
return 0;
}
else
{
return (Int32)result;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你创建的任何一个实现IDisposable的苍蝇都放在一个使用块中.
除非您正在执行显式事务,或者已关闭连接缓存,否则不要继续使用Ado.Net数据库连接.
将DateTimes作为DateTimes传递
给你的变量一个体面的名字,param02没有任何意义,并且计数是误导性的.
不要在需要之前创建东西
你做的事情我个人不会在这个代码中陷入陷阱,特别是在抛弃有关异常的所有有用细节之后再次抛出它.
如果你想这样做,定义一个CustomException,然后抛出新的MyCustomException("检索传送带生产计数错误.",e);
这样,如果需要,我们将能够捕获此特定异常,但您将拥有整个异常链和所有堆栈跟踪.
最后但并非最不重要的是对待包括我在内的所有编码示例,好像它们是由村里白痴厚厚的堂兄建造的.:d