【发布时间】:2021-09-24 18:24:51
【问题描述】:
错误提示 System.Data.Common.DbCommand.ExecuteScalar(...) 返回 null。
protected void Button3_OnClick(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [User] where emailAddress='" + TextBox6.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp >= 1)
{
conn.Open();
string checkPasswordQuery = "select password from [User] where emailAddress='" + TextBox7.Text + "'";
SqlCommand Passcmd = new SqlCommand(checkPasswordQuery, conn);
string password = Passcmd.ExecuteScalar().ToString();
if (password == TextBox7.Text)
{
Session["New"] = TextBox6.Text;
Response.Write("Password is correct");
Response.Redirect("WebForm1.aspx");
}
else
Response.Write("Password is incorrect");
}
else
Response.Write("Username not found");
}
}
}
据说错误发生在写成的行上: string password = Passcmd.ExecuteScalar().ToString();
以下是我的网络配置:
<configuration>
<connectionStrings>
<add name="RegisterConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\User.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
<system.webServer>
【问题讨论】:
-
永远不要连接 SQL 查询。您对 SQL 注入攻击持开放态度。请改用参数化查询。切勿以纯文本形式存储密码。还了解
using语句以及它如何与实现IDisposeable的对象一起使用 -
您的代码存在大量问题:参数化您的查询,否则您将面临注入攻击和错误。
Convert.ToInt32(cmd.ExecuteScalar().ToString())太傻了,直接投吧(int) cmd.ExecuteScalar()。连接和命令对象需要在using块中。不要将密码存储在任何地方,也不要将它们传回和转发到/从服务器,而是盐和散列,并比较散列。一次查询即可查看邮箱地址和密码/hash,无需返回服务器两次。 -
我真的同意你关于存储密码和连接 sql quaries.. 但是,这里列出的代码是用于教育目的,而不是在现实生活中部署。感谢您的关心。
-
However, the code listed here is for educational purposes为什么要以错误的方式教育自己?
标签: c# sql asp.net database webforms