任何人都可以注意到以下功能可能出现的问题:
public string Login(string username, string password) { string result = ""; string select = "SELECT user_id FROM [user] WHERE username = @username AND password = @password"; SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(select, conn); cmd.Parameters.AddWithValue("username", username); cmd.Parameters.AddWithValue("password", password); int userID = 0; try { conn.Open(); userID = (int)cmd.ExecuteScalar(); if(userID > 0) { result = addSession(userID); } } catch(Exception ex) { string sDummy = ex.ToString(); } return result; }
不知道为什么行`userID =(int)cmd.ExecuteScalar(); 抛出一个例外.
谢谢
很可能表中没有用户/密码的行.ExecuteScalar的文档说如果结果集为空则返回null,并且不能将null转换为int.