繁体   English   中英

如何使用if语句使用C#从SQL Server检索一行数据

[英]how to use if statement to retrieve a row of data from sql server using c#

美好的一天

我正在登录页面上工作,如果数据库表中显示了一个值,则用户将能够登录;如果未显示该值,它将为他显示一个更改密码页面。

我想要的是,如果该值不存在,如何编写if语句来检索用户名和密码?

我尝试过的是以下

con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = ("select count (*) from log_sup where ENTITY_DIVISION_CODE = '" + textBox1.Text + "'and DX_NUMBER = '" + textBox2.Text + "'" );
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();

if (dt.Rows[0][0].ToString() == "1" )
{
     Form2 f2 = new Form2();
     f2.Show();
     this.Hide();
}

else
{
     MessageBox.Show("THE USERNAME OR PASSWORD IS INVALID. THIS IS YOUR    " , MessageBoxButtons.OK);
     Form3 F3 = new Form3();
     F3.Show();
     this.Hide();
}
con.Close();

COUNT()是标量函数,因此请使用cmd.ExecuteScalar(); 获得结果作为一个Object 无需使用DataTable并做其他复杂的事情。

以下是简单的解决方案。 请相应地修改它,这只是如何使用ExecuteScalar的帮助。

int result = Convert.ToInt32(cmd.ExecuteScalar());
if(result > 0)
{
    //SUCCESS
}
else
{
    //FAIL
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM