C# 登录功能连接数据库

 string uName = txtUserName.Text.Trim();
            string uPwd = txtUserPwd.Text.Trim();
            txtUserName.Focus();
            if (string.IsNullOrEmpty(uName))
            {
     
                MessageBox.Show("请输入用户名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //txtUserName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(uPwd))
            {
     
                MessageBox.Show("请输入密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //txtUserPwd.Focus();
                return;
            }
            {
     

                //server 认证
                string connString = "server=.;database=StudentDB;uid=sa;pwd=sa123456;";

                //建立与数据库的连接
                SqlConnection conn = new SqlConnection(connString);

                //查询语句
                string sql = "select * from StudentUSer where UserName='"+ uName + "' and UserPwd='"+ uPwd + "'";


                //创建Command对象
                SqlCommand cmd = new SqlCommand(sql, conn);
            

                //打开连接
                conn.Open();

                //执行命令
                object o = cmd.ExecuteScalar();

                //关闭连接
                conn.Close();

                //结果处理
                if (o == null || o == DBNull.Value || (int)o == 0)
                {
     
                    MessageBox.Show("账号或密码输入有误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
     
                    MessageBox.Show("登录成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }

你可能感兴趣的:(C#,c#)