我试图从我的数据库返回一个字符串值,但查询返回“0”,尽管 SELECT 查询的目标是 nvarchar 列。 查询有效且运行正确,使用 SQL-SMS 运行时返回“KYO”。
这是我用于返回数据的方法,它在我使用它的其他地方按预期工作:
public static object GetData(string sql, SqlParameter[] parameters)
{
try
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = sql;
if (parameters != null)
{
foreach (var parameter in parameters)
{
if (parameter != null)
command.Parameters.Add(parameter);
}
}
object result = null;
SqlParameter returnValue = new SqlParameter("ReturnValue", result);
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
connection.Open();
command.ExecuteScalar();
result = command.Parameters["ReturnValue"].Value;
return result;
}
}
}
catch (Exception)
{
throw;
}
}
}
这是抛出转换异常的方法,因为它返回一个 int 而不是一个字符串:
private static String GetManufacturerCode(Int32 manufacturerID)
{
try
{
StringBuilder sql = new StringBuilder();
sql.Append("SELECT ManufacturerCode FROM Manufacturers WHERE ManufacturerID = @ID");
SqlParameter id = new SqlParameter("@ID", manufacturerID);
return(String)DB.GetData(sql.ToString(), new[] { id });
}
catch (Exception)
{
throw;
}
}
我还设置了 returnValue.DbType = DbType.String; 作为测试,它仍然返回一个整数。
我成功使用 GetData(...) 方法的示例是:
public static Int32 GetMonitoredCount()
{
try
{
String GetMonitoredCount = "SELECT COUNT(*) FROM Devices WHERE Monitored = 1 ";
return (Int32)DB.GetData(GetMonitoredCount, null);
}
catch (Exception)
{
throw;
}
}
我认为它可能会返回一个 bool 位,但当我的查询正确执行时,我假设它会返回 1 而不是 0。
为什么返回一个整数?如何使用我的模式返回字符串?
请您参考如下方法:
ReturnValue 始终返回 int - 这是设计使然。
而不是整个 block
object result = null;
SqlParameter returnValue = new SqlParameter("ReturnValue", result);
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
connection.Open();
command.ExecuteScalar();
result = command.Parameters["ReturnValue"].Value;
尝试
connection.Open();
object result = command.ExecuteScalar();
这将返回您的 SQL 语句的真实结果
方法ExecuteScalar本身能够返回值 - 它返回结果集第一行的第一列,当您的查询返回单个值时是理想的选择。
