【问题标题】:Error when using 'BETWEEN' for retrieving a field使用“BETWEEN”检索字段时出错
【发布时间】:2017-04-19 13:12:06
【问题描述】:


我正在做一个项目,但我遇到了一个查询。我的最终目的是从 IP 地址获取国家/地区,为此我有一个包含所有从到 IP 地址的数据库。我的问题是在使用带有“BETWEEN”的查询时出现错误。带有信息的表“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;
    }

最后我得到的错误是:

错误:Riferimento a un oggetto non imppostato su un'istanza di oggetto。
(翻译:错误:对象引用未设置为对象的实例)

我不明白错误在哪里。

【问题讨论】:

  • 将字段 IP_From 和 IP_To 放在单引号之间会将这些名称转换为文字字符串。这两个字符串之间没有UINT
  • 所以我必须删除单引号,它应该可以工作吗?哇,我犯了多么愚蠢的错误XD

标签: c# sql between


【解决方案1】:

将字段 IP_From 和 IP_To 放在单引号之间会将这些名称转换为文字字符串。这两个字符串之间没有 UINT,当代码到达 ExecuteScalar 时,返回值为 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;
}

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多