gpt4 book ai didi

c# - command.ExecuteScalar 没有返回我知道存在的值

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:24 25 4
gpt4 key购买 nike

我试过各种方法,但似乎都行不通。由于结果为空,例程一直返回 0。

这是我的代码:

string strSql = "SELECT [ID] FROM [PurchaseOrder].[dbo].[FMSSupplier] where (ExternalRef = @ExternalRef) and (CompanyID = @CompanyID)";

try
{
SqlCommand command = new SqlCommand(strSql);
command.Connection = new SqlConnection(PO_ConnectionString);
command.CommandType = CommandType.Text;
command.Parameters.Add(new SqlParameter("@ExternalRef",SqlDbType.NVarChar ,50){Value = strExternalRef});
command.Parameters.Add(new SqlParameter("@CompanyID", SqlDbType.Int) { Value = intCompanyID });
if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
var result = command.ExecuteScalar();
if (result != null)
{
return (int)result;
}
else
{
return 0;
}
}

我在SQL Server中测试过,记录存在:

SELECT [ID] 
FROM [PurchaseOrder].[dbo].[FMSSupplier]
WHERE (ExternalRef = 'EDE01') and (CompanyID = 24)

记录 ID 不为零,并且 ConnectionString 在其他实例中有效。

这些是我的两个参数的值:公司 ID = 24strExternalRef = EDE01

最佳答案

首先也是最重要的,检查

 if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();

不保证连接会打开。为什么?

状态可以是:

    Broken
Connecting
//..etc

其次,我不知道您是否为 intCompanyID 、 strExternalRef 值分配了一个值(也许您在没有向我们展示的片段中分配了值)...

任何方式尝试如果这作为第一个调试步骤:

   try
{
SqlCommand command = new SqlCommand(strSql);
command.Connection = new SqlConnection(PO_ConnectionString);
command.CommandType = CommandType.Text;
command.Parameters.Add(new SqlParameter("@ExternalRef",SqlDbType.NVarChar ,50){Value ="EDE01"});
command.Parameters.Add(new SqlParameter("@CompanyID", SqlDbType.Int) { Value = 24});
command.Connection.Open();
var result = command.ExecuteScalar();
if (result != null)
{
return (int)result;
}
else
{
return 0;
}
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

关于c# - command.ExecuteScalar 没有返回我知道存在的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24040311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com