我今天的代码有问题。每当我使用此方法向本地DB添加产品时,它都会抛出一个异常,该异常的内容是“不能将对象从DBNull转换为其他类型”。在进行了一些研究之后,我相信我的问题在于AddProduct方法中的AddProduct参数,但我似乎无法确切地找出是什么原因造成的。我创建的程序仍然正常工作(它添加了产品,然后可以成功地选择),但是当我添加该产品时,它似乎一直抛出这个异常。
有人能提供任何关于问题可能在我的代码中的位置的洞察力吗?如果您需要更多的信息,请毫不犹豫地询问。谢谢你的时间和帮助。
public static bool AddProduct(Product product)
{
SqlConnection connect = MMABooksDB.GetConnection();
string insert = "INSERT Products " + "(ProductCode, Description, UnitPrice) " + "VALUES (@code, @description, @price)";
SqlCommand insertCmd = new SqlCommand(insert, connect);
insertCmd.Parameters.AddWithValue("@code", product.code);
insertCmd.Parameters.AddWithValue("@description", product.description);
insertCmd.Parameters.AddWithValue("@price", product.price);
try
{
connect.Open();
insertCmd.ExecuteNonQuery();
string selectStatement =
"SELECT IDENT_CURRENT('Products') FROM Products";
SqlCommand selectCommand = new SqlCommand(selectStatement, connect);
int ProductCode = Convert.ToInt32(selectCommand.ExecuteScalar());
return true;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connect.Close();
}
}这是产品类
public class Product
{
public string code;
public string description;
public decimal price;
public Product() { }
public Product(string code, string description, decimal price)
{
this.Code = code;
this.Description = description;
this.Price = price;
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string GetDisplayText()
{
return code + ", " + price.ToString("c") + ", " + description;
}
public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep + description;
}
}发布于 2014-04-26 04:10:42
int ProductCode; //declare variable
object dbProductID = selectCommand.ExecuteScalar(); //get the result into object
if(dbProductID !=null || dbProductID != DBNull.Value) //check if it is null
ProductCode = 0; //assign some default value here if it has no productid
else
ProductCode = Convert.ToInt32(dbProductID);//if its has productid cast it into int发布于 2014-04-26 04:04:29
如果产品被添加,我将假设无法转换来自int ProductCode = Convert.ToInt32(selectCommand.ExecuteScalar());,我将添加一个检查,看看那个定标器是否返回null。
https://stackoverflow.com/questions/23306473
复制相似问题