读书人

c#中怎么用SqlDataReader提取数据库中

发布时间: 2013-04-21 21:18:07 作者: rapoo

c#中如何用SqlDataReader提取数据库中的数据?(求解答)
c#中怎么用SqlDataReader提取数据库中的数据?(求解答)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace 记账系统2
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
if (txtName.Text == ""||txtPwd.Text == "")//判断用户名是否为空
{
MessageBox.Show("请输入用户名或密码!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);

}
else
{
try
{

this.sqlConnection1.Open();//打开数据库连接
this.sqlCommand1.Parameters["@username"].Value = this.txtName.Text;//赋值给sql语句中@username
this.sqlCommand1.Parameters["@password"].Value = this.txtPwd.Text;
SqlDataReader reader = this.sqlCommand1.ExecuteReader() ;
int i = int.Parse(this.sqlCommand1.ExecuteScalar().ToString());//查询并返回查询结果集中第一行的第一列忽略其他列
if (i>0)
{
MainForm mform = new MainForm();
AdminMainForm admform = new AdminMainForm();


if (reader.Read())
{

if (reader.GetString(3) == "002")//登录权限普通用户
{

this.Hide();
mform.Show();
}
else if (reader.GetString(3) == "001")//超级用户
{
this.Hide();
admform.Show();
}
reader.Close();
}


}
else
{
MessageBox.Show("用户名或密码错误");
}




}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.sqlConnection1.Close();//关闭数据库连接
}
}
}
}
}
C# SQL 数据库
[解决办法]
怎么不直接返回第一行第一列呢? 这样更加简单!
[解决办法]

引用:
经过一上午的奋战,终于搞定了,问题出在datareader上,就因为没用reader.HasRows,还有就是getstring的错误。真是辛苦死我了,没人理我的痛苦。

你贴出的问题截图跟你的这两个解释根本没有关系,这两个根本不可能显示那样的异常提示。

你的代码中的 sqlConnection1 是怎样定义的呢?你是“瞎改一通”代码然后偶然改“好”的吧?

有些人只愿意抄袭代码、特别怕别人要求他深入一点了解原理。如果你不是这种人,那么我建议你把你的try....catch删除掉,改为using(){....}。

关键是不要写try...catch。否则,一旦有了bug,你的调试器连正确的调试都进不去,你连到底是哪一行、哪一个变量有问题都不能在几秒钟内就发现,你还怎么做开发呢?这些都是滥用try...catch惹的祸。

读书人网 >C#

热点推荐