c#连接数据库的简单实现

c#连接数据库的简单实现

控件布局如下

c#连接数据库的简单实现_第1张图片
代码如下

using System.Data.SqlClient;//添加一条using命令

  //双击textBox2
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            textBox2.UseSystemPasswordChar = true;//设置密码符
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string count = "Server =.;user = sa; pwd = 1;Database =ox;"; //连接数据库字符串
            string sql = "select * from student where sno='" + textBox1.Text.Trim() + "'";//查询要登录的账号进行查询
            SqlConnection con = new SqlConnection(count);//创建con 对象
            SqlCommand cmd = new SqlCommand(sql, con);//创建cmd 对象 
            con.Open();//打开数据库
            SqlDataReader dr = cmd.ExecuteReader();//读取数据库信息
            try
            {
                if (dr.HasRows)//读取行
                {
                    dr.Read();//允许阅读
                    if (textBox2.Text == dr["pwd"].ToString().Trim())//比较输入的密码和数据库里的密码
                        MessageBox.Show("登录成功");//true为成功
                    else
                        MessageBox.Show("登录失败");//flash为失败
                    dr.Close();
                }
            }
            catch (Exception ex)//捕捉错误,这个模块很好用,不要写成空catch()
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally //一定会执行
            {
                con.Close();
            }
        }
    }

欢迎留言交流,可私信我交流。

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