ExecuteReader();不行 [英] ExecuteReader(); not work

查看:183
本文介绍了ExecuteReader();不行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望搜索数据库是表中存在的用户.然后我写这个.但是用黄色标记"SqlDataReader reder = cmd.ExecuteReader();"不能做我的工作吗?
这是问题吗abt"ExecuteReader()" ??????

帮我尽快吧


I want search database is user existing in the table.then i write this. but mark " SqlDataReader reder = cmd.ExecuteReader();" in yellow color and cant do my work?
is this problem abt" ExecuteReader()"???

help me soon as possible


SqlConnection con = new SqlConnection("Data Source=thushan-pc;Initial Catalog=dvd;Integrated Security=True");
bool b=false;
SqlCommand cmd=new SqlCommand("select User_Name from users where=(''"+txtop.Text+"'')",con);
con.Open();

SqlDataReader reder = cmd.ExecuteReader();
if (reder.Read() == true)
b = true;
reder.Close();
cmd.Dispose();

con.Close();
if (b == true)
MessageBox.Show("User here");

推荐答案

首先,不要那样做-它使您容易受到SQL注入攻击的影响.请改用参数化查询(有关详细信息,请参见SqlCommand.AddWithValue).

其次,问题是您的sql命令.假设txtop.Text是"John",请尝试将其写出来:
Firstly, don''t do it like that - it leave you open to an SQL injection attack. Use parameterized queries instead (See SqlCommand.AddWithValue for details).

Secondly, the problem is your sql command. Try writing it out yourself assumeing txtop.Text is "John":
select User_Name from users where=(''John'')


现在尝试使其成为合法的Sql select语句:


Now try making it a legitimate Sql select statement:

SELECT User_Name FROM users WHERE User_Name=''John''


(我将大写的SQL语法词大写,使其更易于解密-值得一提).

如果您将此操作作为参数化查询,则不需要引号,或者...

[edit]手指麻烦:"AddWithValue"中没有"Q"-OriginalGriff [/edit]


(I have capitalised SQL syntax words to make it easier to decipher - worth doing as a general rule).

If you do this as a parameterized query, you won''t need the quotes, either...

[edit]Finger trouble: there is no "Q" in "AddWithValue" - OriginalGriff[/edit]


如果您只需要检查计数,为什么不使用Count?

If you need to just check the count why dont you use Count?

using(SqlConnection con = new SqlConnection("Data Source=thushan-pc;Initial Catalog=dvd;Integrated Security=True"))
{
bool b=false;
using(SqlCommand cmd=new SqlCommand("select Count(User_Name) from users where UserName=''"+txtop.Text+"''",con))
{
  con.Open();

   SqlDataReader reder = cmd.ExecuteReader();
  if (reder.Read())
     if(Convert.ToInt32(dr[0]) == 1)
  {
     b = true;
     break;
  }
reder.Close();
cmd.Dispose();
}
con.Close();
if (b == true)
MessageBox.Show("User here");
}


使用Count而不是仅依赖reder.Read()是一个好习惯.我希望这能帮到您. :rose:


It is a good practice to use Count rather than only to rely on reder.Read(). I hope this will help you. :rose:


这篇关于ExecuteReader();不行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆