System.InvalidOperationException' in System.Data.dll c# 登录到文件。.sql



im在c#上创建e grades项目,通常无法连接到数据库。写https://i.stack.imgur.com/itJuX.png也许你能帮我?不在login.cs工作。我做的最后一份工作是工作。

private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|dienynas.mdf;Integrated Security=True;"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
int id = 0;
bool pass = false;
while (sdr.Read())
{
if (sdr[0].ToString() == textBox1.Text && sdr[0].ToString() == textBox2.Text)
{
pass = true;
id = (int)sdr[0];
break;
}
}
if (pass == false)
{
MessageBox.Show("Password for this user is incorrect");
id = (int)sdr[0];
pass = true;
}
else
{
Form1 frm = new Form1(id);
Hide();
frm.Show();
}
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

问题出在循环后的if语句中。

if (pass == false)
{
MessageBox.Show("Password for this user is incorrect");
id = (int)sdr[0];
pass = true;
}

在那个if块中,您正在访问您的SqlDataReader,它很可能在读取时返回false后退出了while循环,表明没有更多的数据要读取。如果没有数据,那么在尝试读取不存在的数据时会出现错误。

我认为,您退出而没有匹配的原因之一是,除非TextBox1TextBox2都包含匹配的字符串,否则您永远不会匹配。下一行将这些文本框值与完全相同的数据值进行比较。除非这些文本框之间的文本相同,否则此语句将始终为false。

if (sdr[0].ToString() == textBox1.Text && sdr[0].ToString() == textBox2.Text)

我猜你的意图是这样的:

if (sdr[0].ToString() == textBox1.Text && sdr[1].ToString() == textBox2.Text)

编辑
尽管如此,这段代码中仍有很大的重构空间。首先,通常在按钮处理程序中执行数据库操作会导致对话框窗口无响应,这是需要避免的。你还使用了一些其他一次性物品,所以你也应该清理这些物品。我将稍微重写这个函数,向您展示一些清理过程,但我没有时间将其拆分为线程,这超出了您的问题范围。

private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
try
{
var textBox1 = textBox1.Text;
var textBox2 = textBox2.Text;
conn = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|dienynas.mdf;Integrated Security=True;");
conn.Open();
cmd = new SqlCommand("select * from users", conn);
sdr = cmd.ExecuteReader();

int id = -1;
while (sdr.Read())
{
var text0 = sdr[0].ToString();
var text1 = sdr[1].ToString();
// NOTE: You could add the string comparison type here as well
if (text0.Equals(textBox1) && text1.Equals(textBox2))
{
id = (int)sdr[0];
break;
}
}
if (id == -1)
{
MessageBox.Show("Password for this user is incorrect");
}
else
{
Form1 frm = new Form1(id);
Hide();
frm.Show();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sdr?.Dispose();
cmd?.Dispose();
conn?.Dispose();
}
}

最新更新