簡體   English   中英

通過c#和mysql在vb.net中創建登錄頁面,但顯示錯誤消息連接必須有效並打開

[英]create a login page in vb.net by c# & mysql but it shows error message connection must be valid and open

私人無效admin_submit_button_Click(對象發送者,EventArgs e){嘗試{字符串myConnection =“ datasource = localhost; port = 3306; username = root; password = root”;

           MySqlConnection myConn = new MySqlConnection(myConnection);

           MySqlCommand SelectCommand = new MySqlCommand("select * from mws.login_info where login_id='" + this.admin_id_textbox + "'and login_password1='" + this.admin_password_textbox1 + "' and login_password2='" + this.admin_password_textbox2 + "'");
           MySqlDataReader myReader;
           myConn.Open();
           myReader = SelectCommand.ExecuteReader();
           int count = 0;
           while (myReader.Read())
           {
               count = count + 1;
           }
           if (count == 1)
           {
               MessageBox.Show("username and password is correct");
           }
           else
               MessageBox.Show("username and password not correct");
           myConn.Close();
       }
        catch(Exception ex)
       {
           MessageBox.Show(ex.Message);





        }
    }
}

}

您尚未將命令與連接關聯。 您的代碼缺少以下行

SelectCommand.Connection = myConn ;

話雖如此,想象一下我在您的admin_id_textbox中寫了以下文本

' OR login_id like '%' --

您為正確登錄而進行的檢查會怎樣? 它被稱為Sql Injection ,對於每種數據庫訪問來說都是非常危險的情況。

始終使用參數化查詢來構建sql命令,尤其是在使用用戶輸入文本來構建命令的一部分時

private void admin_submit_button_Click(object sender, EventArgs e) 
{ 
    try 
    { 
       string cmdText = @"select * from mws.login_info 
                         where login_id=@id and login_password1=@pwd
                         and login_password2=@pwd2";
       string myConnection = "datasource= localhost;port=3306;username=root;password=root";
       using(MySqlConnection myConn = new MySqlConnection(myConnection))
       using(MySqlCommand SelectCommand = new MySqlCommand(cmdText, myConnection))
       {
           myConn.Open();
           SelectCommand.Parameters.AddWithValue("@id", this.admin_id_textbox);
           SelectCommand.Parameters.AddWithValue("@pwd",this.admin_password_textbox1);
           SelectCommand.Parameters.AddWithValue("@pwd2",this.admin_password_textbox2);
           using(MySqlDataReader myReader = SelectCommand.ExecuteReader())
           {
               if(myReader.HasRows)
                   MessageBox.Show("username and password is correct");
               else
                    MessageBox.Show("username and password not correct");
           }
       }
    }
    catch(Exception ex)
    {
       MessageBox.Show(ex.Message);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM