这是一段C#连接数据库的代码,可是连不成功,提示reader.Close();为null,请高手看看
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Da...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SupermarketStstem
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void sure_Click(object sender, EventArgs e)
{
if (uid.Text.Length == 0)
{
MessageBox.Show("用户名不能为空请输入!");
uid.Focus();
return;
}
if (pwd.Text.Length == 0)
{
MessageBox.Show("密码不能为空请输入!");
pwd.Focus();
return;
}
string connString = @"server=.\sqlexpress;
integrated security=true;database=SuperMarketdb";
string sql = @"select * from Users where UserName='" + uid.Text + "' and UserPassword='" + pwd.Text+"'";
SqlConnection conn = null;
SqlDataReader reader = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("用户名:" + uid.Text + "欢迎使用!");
Main ma = new Main();
ma.Show();
}
else
{
MessageBox.Show("用户名或者密码错误,请重新输入");
uid.SelectAll();
uid.Focus();
return;
}
}
catch (Exception ep)
{
Console.WriteLine("Error:" + ep);
}
finally
{
reader.Close();
conn.Close();
}
}
private void cancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
} 展开
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SupermarketStstem
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void sure_Click(object sender, EventArgs e)
{
if (uid.Text.Length == 0)
{
MessageBox.Show("用户名不能为空请输入!");
uid.Focus();
return;
}
if (pwd.Text.Length == 0)
{
MessageBox.Show("密码不能为空请输入!");
pwd.Focus();
return;
}
string connString = @"server=.\sqlexpress;
integrated security=true;database=SuperMarketdb";
string sql = @"select * from Users where UserName='" + uid.Text + "' and UserPassword='" + pwd.Text+"'";
SqlConnection conn = null;
SqlDataReader reader = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("用户名:" + uid.Text + "欢迎使用!");
Main ma = new Main();
ma.Show();
}
else
{
MessageBox.Show("用户名或者密码错误,请重新输入");
uid.SelectAll();
uid.Focus();
return;
}
}
catch (Exception ep)
{
Console.WriteLine("Error:" + ep);
}
finally
{
reader.Close();
conn.Close();
}
}
private void cancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询