我正在处理一个项目,但遇到了一个查询。我的最终目的是从 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;
}
最后我得到的错误是:
错误:对未在对象实例上设置的对象的引用。
(翻译:错误:未将对象引用设置为对象的实例)
我无法理解错误在哪里。
将字段 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句