C#MySQL数据库登录及注册

首先C#使用MySQL数据库时,需要先添加配置引用文件(mysql.data.dll、mysql.data.entity.dll、mysql.visualstido.dll、mysql.web.dll)。添加完成之后,直接在程序中添加引用即可。

using MySql.Data.MySqlClient;

登录界面: 

登录按钮按下代码:

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox1.Text == "")
                {
                    MessageBox.Show("用户名不能为空");
                }
                else
                {
                    if (textBox2.Text == "")
                    {
                        MessageBox.Show("密码不能为空!");
                    }
                    else
                    {
                        admin_id = textBox1.Text;//获取账号
                        string admin_psw = textBox2.Text;//获取密码
                        string conn = "";
                       
                        conn = "server=182.254.234.37;user id=cccyyy;password=cyg951026; database =bridge";//连接字符串,需要改成你自己的

                        MySqlConnection connection = new MySqlConnection(conn);//创建连接
                        connection.Open();//打开连接                       
                        string sql = string.Format("select count(*) from login where user_name='{0}' and password='{1}'", admin_id, admin_psw);//查询是否有该条记录,根据账户密码
                        MySqlCommand command = new MySqlCommand(sql, connection);//sqlcommand表示要向向数据库执行sql语句或存储过程
                        int i = Convert.ToInt32(command.ExecuteScalar());//执行后返回记录行数

                        if (i > 0)//如果大于1,说明记录存在,登录成功
                        {
                            command = new MySqlCommand("select * from login where user_name='" + admin_id + "'", connection);
                            MySqlDataReader sdr = command.ExecuteReader();
                            sdr.Read();
                            user = sdr["nick_name"].ToString().Trim();

                            Form main = new MainPage();
                            this.Hide();
                            main.Show();
                        }
                        else
                        {
                            MessageBox.Show("用户名或者密码错误!");
                        }
                        connection.Close();
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常错误" + ex);
            }
        }

conn = "server=******;user id=cccyyy;password=cyg951026; database =bridge";

这是连接数据库的MySQL语句。服务可以是远程服务器的IP地址,或者本地,localhost、127.0.0.1或.表示。

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值