注册 登录
编程论坛 C# 论坛

用户登录与数据库连接问题

程落薰 发布于 2013-12-06 19:39, 696 次点击
各位大神,我做了一个用户登录窗体,需要连接到数据库验证输入的用户名和密码是否正确,若是,则显示“登录成功”,否则,显示“用户名或密码不正确”。代码如下:
 string u = username.Text.Trim();
            string p = password.Text.Trim();

            String strCon = " Data Source=xxlab213-24;Password=sa;User ID=sa;DataBase=ProductsDB";
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = con.CreateCommand();
            string sql = string.Format("select * from Users where UserName =u  and Password = p", u, p);
            int result = 0;        //如果大于1,则有数据存在

            try
            {
                   con.Open();
                   result = (int)cmd.ExecuteScalar();
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            if (result > 0)
                MessageBox.Show("登录成功!");
            else
                MessageBox.Show("用户名或密码错误 !");


问题:即使输入正确的用户名和密码,也只显示“用户名或密码错误”。
求指教!!!!!!!
5 回复
#2
qw11617485792013-12-10 14:26
string sql ="select * from Users where UserName ="+u+"and Password ="+p;
#3
Evelia2013-12-10 16:28
你这SQL语句貌似就没执行过...
#4
alina41220152013-12-11 11:18
这样写应该可以      
private void Connection()
        {
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection("Data Source=localhost,4111;Initial Catalog=DB;User ID=sa;Pwd=123456;Integrated Security=false;");
                connection.Open();

                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                = "Select * From TableName";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   //用这个代替MessageBox.Show("用户名或密码错误 !"),这样不光是用户名密码错误会提示,各种连接错误都会提示
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    MessageBox.Show("登录成功!");
                }
            }
        }
#5
alina41220152013-12-11 11:21
回复 4楼 alina4122015
搞错了~是登录FRM呀!不好意思~路过
#6
gcf09372018-07-17 11:23
我学习学习,顶一下下
1