c# - 未设置对象引用
问题描述
public static Boolean ValidateUser(string struser, string strpass)
{
// Establish connection information
SqlConnection conn_string = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Data Source=137.145.169.3;Initial Catalog=SICI4266;Persist Security Info=True;User ID=SICI4266G3;Password=*******"].ConnectionString);
// Establish SQL command
SqlCommand sql_comm = new SqlCommand("SELECT count(userID) FROM HIEPA.HIEPA_USERS where UserName = @usuario and UserPassword = @contrasena ; ", conn_string);
// Provide Parameter values
sql_comm.Parameters.AddWithValue("@usuario", struser);
sql_comm.Parameters.AddWithValue("@contrasena", strpass);
// Open the connection
conn_string.Open();
// Execute the SQL command and assign the resulting value to an integer variable
Int32 intUserCount = Convert.ToInt32(sql_comm.ExecuteScalar());
// Close the connection
conn_string.Close();
// Evaluate the integer variable content; greater than cero is a valid combination
if (intUserCount == 1)
{
return true;
}
else
{
return false;
}
}
有人能告诉我为什么会提示这个错误吗?
解决方案
异常结果中以红色突出显示的行中的这个表达式是null
:
System.Configuration.ConfigurationManager.ConnectionStrings["Data Source=137.145.169.3;Initial Catalog=SICI4266;Persist Security Info=True;User ID=SICI4266G3;Password=*******"]
它为空,因为该Connection[]
属性需要字符串的名称,而不是完整的字符串。它正在尝试在集合中查找字符串,没有找到那么大的长文本块,因此返回null
。
鉴于上述情况,您然后尝试引用引用的.Connection
字符串属性null
。就好像你已经这样做了:
null.ConnectionString;
要么更改该代码以使用文件中列出的连接字符串的名称web.config
,要么因为您已经拥有整个字符串,所以只需将该字符串直接提供给SqlConnection()
构造函数。无论哪种方式,该代码都应该清理一些:
//comments should focus on "why", rather than "what"
public static Boolean ValidateUser(string struser, string strpass)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn string name"].ConnectionString))
using (var sql_comm = new SqlCommand(""SELECT count(userID) FROM HIEPA.HIEPA_USERS where UserName = @usuario and UserPassword = @contrasena ; ", conn))
{
//Don't use AddWithValue(). It forces ADO.Net to guess about parameter types.
//Use exact column types and lengths instead
sql_comm.Parameters.Add("@usuario", SqlDbType.NVarChar, 50).Value = struser;
//Dear God, please tell me you're not using a plain-text password? That's a HUGE mistake!
sql_comm.Parameters.Add("@contrasena", SqlDbType.NVarChar, 180).Value = strpass;
conn.Open();
return (1 == (int)sql_comm.ExecuteScalar());
}
}
推荐阅读
- flutter - Flutter UI - 行和列
- javascript - 我试图从 REACTJS 中的输入中获取值,但结果为空
- bash - 如何向“Bash”函数添加默认参数?
- java - Flink 1.13 UnsupportedOperationException
- css - 需要更正:css中的checked事件
- python - 打印 unicode 字符名称 - 例如 'GREEK SMALL LETTER ALPHA' - 而不是 'α'
- list - 如何在列表中添加十六进制字符串变量?
- .net - 如何通过反射在dotnet中制作更简单的代码以实现多用途?
- node.js - 请推荐一些使用 Nodejs 创建soap请求的课程/教程/书籍
- c# - 如何映射字典
并列出 使用自动映射器?