转换错误从数据库中SMALLINT到C#可空INT数据库中、错误、INT、SMALLINT

2023-09-05 04:18:46 作者:你好萌

我在 SMALLINT 数据类型的数据库security_role_cd列。我使用下面的code到可空INT 变量选择此列。

我收到以下错误:

  

错误3的条件EX pression类型无法确定,因为没有之间的空与短

隐式转换

什么是正确的code克服这种错误?

  SELECT R.security_role_cd从Security_Role R其中security_role_name ='管理员'
 

C#

 诠释? roleID = NULL;
        字符串的CommandText =SELECT R.security_role_cd从Security_Role R其中security_role_name = @rolename;
        SqlCommand的命令=新的SqlCommand(CommandText中,连接);
        command.CommandType = System.Data.CommandType.Text;
        command.Parameters.AddWithValue(@角色名,角色名);
        SqlDataReader的readerRole = Command.ExecuteReader却();
        如果(readerRole.HasRows)
        {
            而(readerRole.Read())
            {
                roleID = readerRole.GetInt16(0)== 0?空:readerRole.GetInt16(0);

            }
        }
        readerRole.Close();
 

解决方案

它只是需要知道如何的键入的的

  roleID = readerRole.GetInt16(0)== 0? (INT?)空:(INT)readerRole.GetInt16(0);
 
Java知识点 DDL之操作数据库

我个人倒缓存值,但:

  INT TMP = readerRole.GetInt16(0); //隐式扩大在这里诠释
roleID = TMP == 0? (INT?)空:TMP;
 

虽然我也想叫成疑问转动的智慧 0 - 最好使用 IsDBNull以便 - 是这样的:

 如果(reader.IsDBNull(0)){
    roleID = NULL;
} 其他 {
    roleID =(int)的readerRole.GetInt16(0);
}
 

I have a security_role_cd column in database of smallint datatype. I am selecting this column using following code into a nullable int variable.

I am getting following error:

Error 3 Type of conditional expression cannot be determined because there is no implicit conversion between 'null' and 'short'

What is the correct code to overcome this error?

SELECT R.security_role_cd  FROM Security_Role R WHERE security_role_name = 'Admin'

C#

        int? roleID = null;
        string commandText = "SELECT R.security_role_cd  FROM Security_Role R WHERE security_role_name = @roleName";
        SqlCommand command = new SqlCommand(commandText, connection);
        command.CommandType = System.Data.CommandType.Text;
        command.Parameters.AddWithValue("@roleName",roleName);
        SqlDataReader readerRole = command.ExecuteReader();
        if (readerRole.HasRows)
        {
            while (readerRole.Read())
            {
                roleID = readerRole.GetInt16(0) == 0 ? null : readerRole.GetInt16(0) ;

            }
        }
        readerRole.Close();

解决方案

It just needs to know how to type the null:

roleID = readerRole.GetInt16(0) == 0 ? (int?)null : (int)readerRole.GetInt16(0);

Personally I'd cache the value though:

int tmp = readerRole.GetInt16(0); // implicit widening to int here
roleID = tmp == 0 ? (int?)null : tmp;

Although I'd also call into doubt the wisdom of turning a 0 into a null - better to use IsDBNull - something like:

if(reader.IsDBNull(0)) {
    roleID = null;
} else {
    roleID = (int)readerRole.GetInt16(0);
}