[英]datatable.rows.count always returns 0
I'm creating a simple web service to authenticate a user. 我正在创建一个简单的Web服务来验证用户身份。
I have a problem filling the datatable(used to store the results of a select statement) properly, 'dt.rows.count' (dt is the name of the datatable) always returns 0 even if the select statement returns nothing. 我在正确填充数据表(用于存储选择语句的结果)时遇到问题,即使选择语句未返回任何内容,“ dt.rows.count”(dt是数据表的名称)也始终返回0。 I've tried clearing the datatable before filling it, and after the if condition as well, but to no avail, I get the same result. 我尝试在填充数据表之前清除数据表,并且在if条件之后也尝试清除数据表,但无济于事,我得到了相同的结果。
Would really appreciate any advice on how to proceed. 真的很感谢任何有关如何进行的建议。
[WebMethod]
public string Authen(string a, string b)
{
var con = new SqlConnection("Data Source=SERVER-SQL;Initial Catalog=DECA-DB;Persist Security Info=True;User ID=sa;Password=*****");
var sda = new SqlDataAdapter("SELECT * FROM Login_Matrix WHERE Username = ' " + a + " ' AND Password = ' " + b + " '", con);
var dt = new DataTable();
con.Open();
dt.Clear();
sda.Fill(dt);
con.Close();
int x = dt.Rows.Count;
//return (x);
if ( x >0)
{
dt.Clear();
return ("In");
}
else
{
dt.Clear();
return ("out");
}
}
}
Adding a space after and before the single quotes makes your query search for inexistant user names and passords (like " Steve ") and it return no records 在单引号之前和之前添加空格使查询搜索不存在的用户名和密码(例如“ Steve”),并且不返回任何记录
A quick fix could be 快速修复可能是
var sda = new SqlDataAdapter(@"SELECT * FROM Login_Matrix
WHERE Username = '" + a + "'
AND Password = '" + b + "'", con);
but this is very dangerous. 但这很危险。
This code is vulnerable to Sql Injection attacks . 此代码容易受到Sql Injection攻击 。
You should use parameters 您应该使用参数
var sda = new SqlDataAdapter(@"SELECT * FROM Login_Matrix
WHERE Username = @uname
AND Password = @pwd", con);
sda.SelectCommand.Parameters.Add("@uname", SqlDbType.NVarChar).Value = a;
sda.SelectCommand.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = b;
And on the same line about security, another thing to consider as soon as possible, is that storing plain text password in your database is a really big security risk. 就安全性而言,尽快考虑的另一件事是,将纯文本密码存储在数据库中确实存在很大的安全风险。 You should search how to salt and store an hash of the password 您应该搜索如何添加密码并存储哈希值
There are other parts of this code to improve. 此代码还有其他部分需要改进。
So you can rewrite your code as: 因此,您可以将代码重写为:
string cmdText = @"IF EXISTS(SELECT 1 FROM Login_Matrix
WHERE Username = @uname AND Password = @pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection con = new SqlConnection("....."))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
int result = (int)cmd.ExecuteScalar();
return ( result == 1 ? "In" : "out");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.