SqlDataAdapter.Fill(dt)意外错误

时间:2018-11-29 21:23:38

标签: c# sql database ado.net

private void button1_Click(object sender, EventArgs e)
{
   SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\mohamma ali\Documents\Visual Studio 2015\Projects\WindowsFormsApplication4\WindowsFormsApplication4\MyLib_DB.mdf ;Integrated Security=True;Connect Timeout=30");
   string query =  "Select *  From User_Registration where UserID = '" + username_textbox.Text.Trim() + "' & Password = '" + password_text.Text.Trim() + "'";
   SqlDataAdapter sda = new SqlDataAdapter(query, con);
   DataTable dt = new DataTable ();
   sda.Fill(dt);

   if (dt.Rows.Count == 1)
   {
       mainmenu main = new mainmenu();
       this.Hide();              
       main.Show();
    }
    else
    {
          MessageBox.Show("Please Check usename and password");
    }
}

它在sda.fill(dt)返回意外错误吗?

2 个答案:

答案 0 :(得分:2)

在SQL中,您应该使用and而不是&。另外,您应始终使用parameterized queries来避免SQL Injection。所以您的查询应该是这样的:

  string query =  "Select *  From User_Registration where UserID = @userName and Password = @password";
  sda.SelectCommand.Parameters.AddWithValue("@userName ", username_textbox.Text.Trim());
  sda.SelectCommand.Parameters.AddWithValue("@password", password_text.Text.Trim());

答案 1 :(得分:1)

private void button1_Click(object sender, EventArgs e)
{
    {
        string commandText = "Select * From User_Registration where UserID = @UserID  and Password = @Password ";

        using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\mohamma ali\Documents\Visual Studio 2015\Projects\WindowsFormsApplication4\WindowsFormsApplication4\MyLib_DB.mdf ;Integrated Security=True;Connect Timeout=30"))
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.AddWithValue("@UserID", username_textbox.Text.Trim());
            command.Parameters.AddWithValue("@Password", password_text.Text.Trim());

            try
            {
                connection.Open();
                sda.SelectCommand = command;

                DataTable dt = new DataTable();
                sda.Fill(dt);

                if (dt.Rows.Count == 1)
                {
                    mainmenu main = new mainmenu();
                    this.Hide();
                    main.Show();
                }
                else
                {
                    MessageBox.Show("Please Check usename and password");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }