private int MyTimeValue()
{
int Value = 0;
string connectionString = GetConfigurationSettingValue("ConnectionString");
int Days = 120;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("select [dbo].[My_function] (@Span)", connection))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@Span", Days));
Value = Convert.ToInt32(cmd.ExecuteScalar());
}
}
return (Value);
}
我越来越Object cannot be cast from DBNull to other types.
如何使用try
和catch
处理此处的空异常
请帮助我语法。
您可以在转换前进行验证
object result = cmd.ExecuteScalar();
if(result != null)
Value = Convert.ToInt32(result);
并添加参数如下
cmd.Parameters.AddWithValue("@Span", Days);
作为旁注,不需要第 cmd.CommandType = System.Data.CommandType.Text;
行。 默认命令类型为文本
错误就在这里:
Value = Convert.ToInt32(cmd.ExecuteScalar());
试试这个:
var result = cmd.ExecuteScalar();
Value = result == DBNull.Value ? 0 : Convert.ToInt32(result);
注意:您的命令字符串对我来说似乎也是错误的。
您需要首先检查 ExecuteScalar 返回的值是否为 null,以便在尝试将对象强制转换为 Int32 时不会发生异常。
private int MyTimeValue()
{
int Value = 0;
string connectionString = GetConfigurationSettingValue("ConnectionString");
int Days = 120;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("select [dbo].[My_function] (@Span)", connection))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@Span", Days));
object o=cmd.ExecuteScalar();
if(o!=null)
Value = Convert.ToInt32(o);
}
}
return (Value);
}
这可以通过两种方式完成。
案例 1:处理特定异常
private int MyTimeValue()
{
int Value = 0;
try
{
string connectionString = GetConfigurationSettingValue("ConnectionString");
int Days = 120;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("select [dbo].[My_function] (@Span)", connection))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@Span", Days));
Value = Convert.ToInt32(cmd.ExecuteScalar());
}
}
catch(NullReferenceException ex)
{
\Handle Exception
}
return (Value);
}
情况 2:检查变量是否为 Null,并捕获其他意外异常的常规异常
private int MyTimeValue()
{
int Value = 0;
try
{
string connectionString = GetConfigurationSettingValue("ConnectionString");
int Days = 120;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("select [dbo].[My_function] (@Span)", connection))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@Span", Days));
var result = cmd.ExecuteScalar();
if(result !=null)
Value = Convert.ToInt32(result );
}
}
catch(Exception ex)
{
\For handling unexpected exceptions
}
return (Value);
}
试试这个
Value = cmd.ExecuteScalar();
if (((Value != null) || (Value != DBNull.Value)))
{
Value =(int)Value ;
}