在 C# 中选择 MySQL 数据 [英] Select MySQL Data in C#

查看:40
本文介绍了在 C# 中选择 MySQL 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 c# 登录该程序,我的用户名和密码存储在 phpmyadmin 中的 SQL 数据库中.这是我目前所拥有的.

I want to login to the program using c#, with my username and password that's stored to the SQL Database in phpmyadmin. This is what I have so far.

private void button1_Click(object sender, EventArgs e)
        {
            MySqlConnection connection;
            string server = "localhost";
            string database = "login";
            string uid = "root";
            string password = "";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";


            connection = new MySqlConnection(connectionString);

            try
            {
                connection.Open();
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    Form1 frm = new Form1(this);
                    frm.Show();
                    Hide();
                }
                else
                {
                    MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
            }
        }

它连接到数据库,但是我不希望它显示 form1 直到输入了有效的用户名和密码.我猜我需要使用 SELECT * FROM 但我不确定如何去做.

It connects to the database, however I don't want it to show the form1 Until both a valid Username and Password have been entered. I'm guessing I need to use SELECT * FROM but I'm not exactly sure how to go about it.

推荐答案

可以用这种方式查看用户名和密码是否匹配

You can use this way to see if username and password match

MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = @username and password=@password";
command.Parameters.Add("@username", txtUserName.Text);
command.Parameters.Add("@password", txtPassword.Text);
var count = cmd.ExecuteScalar();

if(count>0)
    //Logged In

只是说,如果你使用像这样的查询

Just to say, if you use a query like

cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'";

您将接受 SQL 注入

You will be open to SQL Injection

警告

正如史蒂夫在评论中提到的,明文密码是一个与字符串连接相同数量级的漏洞

As Steve mentioned in comments Passwords in clear text are a vulnerability of the same magnitude of string concatenation

这篇关于在 C# 中选择 MySQL 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆