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

C#与数据库连接出错

wuyue970907 发布于 2013-12-19 19:39, 607 次点击
private void btnlogin_Click(object sender, EventArgs e)
        {
            //password=123456789;Persist Security Info=True;User ID=sa;Initial Catalog=学生成绩管理系统;Data =Source=LQ-PC\\SQLEXPRESS
            string connString = "Data Source=吴月-PC;Initial Catalog=学生成绩管理系统;Integrated Security=True";
            SqlConnection connection = new SqlConnection(connString);
            string label2 = type.Text;
            string userName = txtname.Text;
            string password = txtpassword.Text;
            string sql = string.Format("select count(*) from 用户登录 where  用户名='{0}'and 密码='{1}'and 类别='{2}'", txtname.Text, txtpassword.Text,type.Text);


            try
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sql, connection);

                int num = (int)command.ExecuteScalar();
                if (num > 0)
                {
                    if (type.Text == "学生")
                    {
                        MessageBox.Show("欢迎进入学生成绩系统!", "登录成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Form2 dd = new Form2();
                        dd.Show();
                        this.Visible = false;
                    }
                    else if (type.Text == "教师")
                    {
                        MessageBox.Show("欢迎进入学生成绩系统!", "登录成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Form3 dd = new Form3();
                        dd.Show();
                        this.Visible = false;
                    }
                    else if (type.Text == "管理员")
                    {
                        MessageBox.Show("欢迎进入学生成绩系统!", "登录成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Form4 dd = new Form4();
                        dd.Show();
                        this.Visible = false;
                    }

                }
                else
                {
                    txtpassword.Text = "";
                    MessageBox.Show("您输入的用户名或密码错误!", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
           /* catch (Exception ex)
            {
                MessageBox .Show(ex.Message ,"操作数据库出错!",MessageBoxButtons .OK,MessageBoxIcon.Exclamation);
            }*/
             finally
             {
                 connection.Close();
             }
            
            

           
       }

运行时出现:对象名,’用户登录‘无效,请问什么原因
2 回复
#2
shangsharon2013-12-20 15:49
string sql = string.Format("select count(*) from 用户登录 where  用户名='{0}'and 密码='{1}'and 类别='{2}'", txtname.Text, txtpassword.Text,type.Text);

表名,列明最好用"[]"括起来
string sql = string.Format("select count(*) from [用户登录] where  [用户名]='{0}'and [密码]='{1}'and [类别]='{2}'", txtname.Text, txtpassword.Text,type.Text);
#3
3037709572013-12-20 16:14
连接字符串给的不对。
1