使用 'BETWEEN' 检索字段时出错

Error when using 'BETWEEN' for retrieving a field


我正在做一个项目,但遇到了一个查询。我的最终目的是从 IP 地址获取国家/地区,为此我有一个包含所有从 IP 地址到 IP 地址的数据库。我的问题是在使用带有 'BETWEEN' 的查询时出现错误。带有信息的 table 'tb_CountryIP' 是这样的(我只代表了第一条和最后一条记录):

|   ID   |   IP_From   |   IP_To    |   Country   |
|    1   |   16777216  |  16777471  |     AU      |
                      ...
| 148614 | 3758095872  | 3758096127 |     SG      |

我使用查询的函数是:

private string GetCountry(uint ipNum)
    {
        string resultStr= null;
        string query = $@"SELECT Country FROM tb_CountryIP WHERE '{ipNum.ToString()}' BETWEEN 'IP_From' AND 'IP_To'";

        try
        {
            using(SqlConnection sqlConn = new SqlConnection(ConnectionStr))  // ConnectionStr reference to the connection string of the database
            {
                sqlConn.Open();

                using(SqlCommand sqlComm = new SqlCommand(query, sqlConn))
                {
                    resultStr= sqlComm.ExecuteScalar().ToString();
                }
            }
        }
        catch(Exception ex)
        {
            resultStr= $"Error : {ex.Message}";
        }
        return resultStr;
    }

最后我得到的错误是:

Error : Riferimento a un oggetto non impostato su un'istanza di oggetto.
(Translated: Error: Object reference not set to an instance of an object)

我不明白错误在哪里。

将字段 IP_From 和 IP_To 放在单引号之间会将这些名称转换为文字字符串。这两个字符串之间没有 UINT,当代码到达 ExecuteScalar 时,return 值为 NULL。当然,尝试将 NULL 转换为字符串会引发臭名昭著的 NullReferenceException。

private string GetCountry(uint ipNum)
{
    string resultStr= null;
    string query = $@"SELECT Country 
                    FROM tb_CountryIP 
                    WHERE {ipNum} >= IP_From 
                      AND {ipNum} <= IP_To";

    try
    {
        using(SqlConnection sqlConn = new SqlConnection(ConnectionStr)) 
        using(SqlCommand sqlComm = new SqlCommand(query, sqlConn))
        {
            sqlConn.Open();
            object result = sqlComm.ExecuteScalar();
            if(result != null)
                resultStr = result.ToString();
        }
    }
    catch(Exception ex)
    {
        resultStr= $"Error : {ex.Message}";
    }
    return resultStr;
}