1
我试图从我的数据库中返回一个字符串值,但是查询返回“0”,尽管SELECT查询的目标是一个nvarchar列。 查询有效且正确运行,当使用SQL-SMS运行时返回“KYO”。对Nvarchar列的返回SELECT查询
这是方法,因为预计在我使用它的其他地方,其工作的,我使用的返回数据:
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;
}
}
我认为它可能会返回一个布尔位,但作为我的查询执行正确我会假设它会返回1不为0。
为什么要返回一个整数?我怎样才能使用我的模式返回一个字符串?