繁体   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