使用SqlDatareader读取数据问题

来源:百度知道 编辑:UC知道 时间:2024/06/07 03:37:47
问:使用SqlDataReader读取数据后,不能得到正确数据,得到的结果是,如果查找正确返回1,不正确返回0,没有返回希望查找到的数据
代码如下:

private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.ToString() == "" || textBox2.Text.ToString() == "")
{
MessageBox.Show("用户名或密码不能为空!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string s = "Data Source=. \\SQLEXPRESS;AttachDbFilename=D:\\medicament.mdf;";
s += "Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(s);
string s1="select count(*) from [User] where user_Name='"+textBox1.Text.ToString()+"' and user_Password='"+textBox2.Text.ToString()+"'";
SqlCommand c

加断点单步调试,如果reader确实有值的话那么考虑页面事件周期,如果reader没有值,那么检查连接和sql
顺便说一下,你这sql语句返回的是用户名和用户密码匹配的条数
是一个单行单列的数据集

首先有一个误区,textBox1.Text已经获取到string内容了,不需要再ToString()了。

string s1="select count(*) from [User] where user_Name='"+textBox1.Text.ToString()+"' and user_Password='"+textBox2.Text.ToString()+"'";

你如果是想返回查找结果的数据集的话,那么是你的SQL语句写错了。

string s1="select user_Name from [User] where user_Name='"+textBox1.Text.ToString()+"' and user_Password='"+textBox2.Text.ToString()+"'";

SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
label4.Text = "你登录的用户名是:" + reader[0].ToString();
}

把sql输出出来,拿到数据库里执行一下看好不好使