我有下面的 Controller 获取帐户作为输入参数,它连接到 Sql 服务器并且必须调用传递帐户的存储过程。如果帐户不存在,存储过程将插入一条新记录并更新它当已经在那里时
string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
DbConnection.Open();
SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
command.CommandType = CommandType.StoredProcedure;
//create type table
DataTable table = new DataTable();
table.Columns.Add("AccountID", typeof(string));
table.Rows.Add(Account);
SqlParameter parameter = command.Parameters.AddWithValue("@Account_TT", table);
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "Account_TT";
下面是web.config中的ConnectionString
<connectionStrings>
<add name="DBConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
存储过程是这样的
ALTER PROCEDURE [dbo].[usp_InserUpadte]
@account_TT AS account_TT READONLY
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION;
MERGE dbo.[Account] prj
USING @account_TT tt
ON prj.AccountID = tt.AccountID
WHEN MATCHED THEN UPDATE SET prj.CounterSeq = prj.CounterSeq+1
WHEN NOT MATCHED THEN INSERT (AccountID,CounterSeq)
VALUES (tt.AccountID, 1);
COMMIT TRANSACTION;
END;
创建表类型的地方
CREATE TYPE account_TT AS TABLE
(
AccountID nvarchar(50),
)
GO
当我尝试调用 API 时,它没有抛出任何异常,但也没有使用存储过程创建/更新任何记录。我试图调试添加断点。我看到了
DbConnection.Open();
看起来连接没有打开。我可以通过 SQL Management Studio 从我正在使用的同一台服务器连接到 SQL 服务器。谁能告诉我可能是什么问题。
请您参考如下方法:
你可能已经打开了连接。打开连接的正确方法
string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
using(SqlConnection dbConnection = new SqlConnection(strcon))
{
if (dbConnection.State==ConnectionState.Closed)
{
con.Open();
}
}
