[英]Insert/Update in asp.net and SQL SERVER 2008
I am trying to insert a record if requested prodName
doesnot exist in database. 如果数据库中不存在请求的
prodName
我将尝试插入一条记录。 If it exists I want to update the value of quantity
attribute. 如果存在,我想更新
quantity
属性的值。 I have used the following it neither inserts nor Updates any record. 我使用以下方法,既不插入也不更新任何记录。 I get following exception:
我得到以下异常:
ExecuteScalar requires an open and available Connection. The connection's current state is closed
This is the code 这是代码
public static void manageStock(CompanyStock stock)
{
///// Check if record exists/////////
cmd = new SqlCommand("select count(*) from tblStock where prodName=@prodName", con);
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar(); //returns null if doesnt exist
con.Close();
if (count > 0)
{
cmd = new SqlCommand("update tblStock set quantity = @quantity where prodName=@prodName", con);
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
cmd.Parameters.AddWithValue("@quantity", stock.quantity);
}
else
{
cmd = new SqlCommand("insert into tblStock(prodName,quantity) values (@prodName, @quantity)", con);
cmd.Parameters.AddWithValue("@prodName",stock.prodName);
cmd.Parameters.AddWithValue("@quantity",stock.quantity);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
Edited I edited my code. 编辑我编辑了代码。 It works fine now.
现在工作正常。 I had to open my connection before executing
ExecuteScalar
But I want to know the standard way of writing this opening and closing stuff. 我必须在执行
ExecuteScalar
之前打开连接,但是我想知道编写此打开和关闭内容的标准方法。 It looks kind of haphazard. 看起来有点偶然。 How can I improve this?
我该如何改善?
You can use Convert.ToInt32() method for converting the result into integer value. 您可以使用Convert.ToInt32()方法将结果转换为整数值。
if the value is null
it converts it into 0
. 如果该值为
null
,则将其转换为0
。
Try This: 尝试这个:
int count = Convert.ToInt32(cmd.ExecuteScalar());
Consider using MERGE clause in sql-server. 考虑在sql-server中使用MERGE子句。 Here is a good Microsoft article you can use.
这是您可以使用的很好的Microsoft文章 。
What does it do when you step through the code? 当您逐步执行代码时,它会做什么?
In some SQL collations (Latin1_General_BIN for example), variables are case sensitive. 在某些SQL归类中(例如,Latin1_General_BIN),变量区分大小写。 In your first select statement you have @
P
rodName in your query and @ p
rodName in your parameters collection. 在第一个select语句中,查询中有@
P
rodName,参数集合中有@ p
rodName。 If you have a case sensitive collation, you're never getting past this part. 如果您有区分大小写的排序规则,那么您永远都不会错过这一部分。 Right-click on the database in Management Studio and click Properties to find the collation.
右键单击Management Studio中的数据库,然后单击“属性”以查找排序规则。
Error say that there's no connection.May u check first of all that issue so 错误说没有连接,可以先检查一下所有问题
Check connection and if is not null and exist at this point check it con.State = Open or any other value. 检查连接,如果不为空并且存在,请检查con.State = Open或任何其他值。 I connection state is closed open it.But first of all where is connections declaration ?
我的连接状态是关闭打开的。但是,连接声明首先在哪里? i don't see it in your code.
我在您的代码中看不到它。
TRY THIS : 尝试这个 :
//USING THE STATEMNET USING IT WILL TAKE CARE TO DISPOSE CONNECTION AND PLACE TRY CATCH WITHIN PROCS
{
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings("connectionString"))) {
if (cnn.State == System.Data.ConnectionState.Closed)
cnn.Open();
using (SqlCommand cmd = new SqlCommand()) {
try {
cmd.Connection = cnn;
cmd.CommandText = "YOUR SQL STATEMENT";
int I = Convert.ToInt32(cmd.ExecuteNonQuery);
if (I > 0)
{
cmd.CommandText = "YOUR SQL STATEMENT";
//ADDITIONAL PARAMTERES
}
else
{
cmd.CommandText = "YOUR SQL STATEMENT";
//ADDITIONAL PARAMETERS
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
}
You can try this code. 您可以尝试此代码。 First write a stored procedure:
首先写一个存储过程:
CREATE PROCEDURE sprocquanupdateinsert
@prodName nvarchar(250),
@quantity int
AS
BEGIN
UPDATE tblStock
SET quantity = @quantity
WHERE prodName = @prodName
IF @@ROWCOUNT = 0
INSERT INTO tblStock(prodName, quantity)
VALUES (@prodName, @quantity)
END
GO
Then in code behind you can use this 然后在后面的代码中可以使用它
using (conn)
{
SqlCommand cmd = new SqlCommand("sprocquanupdateinsert", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
cmd.Parameters.AddWithValue("@quantity", stock.quantity);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.