ASP.NET中Connection、Command、DataRead操作数据库

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "insert,delete,editor,query,browse  test!";
            //string connstr = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
            //SqlConnection conn = new SqlConnection();
            //conn.ConnectionString = connstr;
            Button7.Visible = false;
        }

        protected void Button6_Click(object sender, EventArgs e)
        {
            this.browseinfo(this.TextBox1.Text);
        }
        //############################浏览数据开始##########################
        public void browseinfo(string username)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
            {
                try
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Select * FROM USERINFO";
                    SqlDataReader reader = cmd.ExecuteReader();
                    this.GridView1.DataSource = reader;
                    this.GridView1.DataBind();
                    reader.Close();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }

            }
        }

        //#########################查询数据开始#####################
        protected void Button5_Click(object sender, EventArgs e)
        {
            this.queryinfo(this.TextBox1.Text);
        }
        public void queryinfo(string username)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
            {
                try
                {
                    conn.Open();
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Select * FROM USERINFO Where USERNAME='" + username + "'";
                    SqlDataReader reader = cmd.ExecuteReader();
                    this.GridView1.DataSource = reader;
                    this.GridView1.DataBind();

                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }
        //##############################插入数据开始################################
        protected void Button2_Click(object sender, EventArgs e)
        {
            this.inserinfo(this.TextBox1.Text, this.TextBox2.Text);
        }
        public void inserinfo(string username, string password)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
            {
                if (username == "" || password == "")
                {
                    Response.Write("<script>alert('username or password is null!');</script>");
                    return;
                }
                try
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Select  COUNT(*)  FROM USERINFO Where USERNAME='" + username + "'";
                    int i = (int)cmd.ExecuteScalar();
                    if (i > 0)
                    {
                        Response.Write("<script>alert('添加的用户名已经存在!')</script>");
                        return;
                    }
                    cmd.CommandText = "Insert INTO USERINFO (USERNAME,PASSWORD) values ('" + username + "','" + password + "')";
                    // cmd.ExecuteNonQuery();
                    Response.Write("<script>alert('success!insert into table'+'" + (int)cmd.ExecuteNonQuery() + "'+'条数据')</script>");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }

        protected void Button7_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
        }
        //##############################删除数据开始################################
        protected void Button3_Click(object sender, EventArgs e)
        {
            this.deleteinfo(this.TextBox1.Text);
        }
        public void deleteinfo(string username)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
            {
                try
                {
                    if (username == "")
                    {
                        Response.Write("<script>alert('请输入要删除的用户名!')</script>");
                        return;
                    }
                    conn.Open();
                    SqlCommand cmd = conn.CreateCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Delete FROM USERINFO Where USERNAME = '" + username + "'";

                    Response.Write("<script>alert('删除" + (int)cmd.ExecuteNonQuery() + "'+'条数据')</script>");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }
        //##############################编辑数据开始################################
        protected void Button4_Click(object sender, EventArgs e)
        {
            this.editorinfo(this.TextBox1.Text, TextBox2.Text);
        }
        public void editorinfo(string username, string password)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
            {
                try
                {
                    if (username == "")
                    {
                        Response.Write("<script>alert('请输入要修改的用户名!')</script>");
                        return;
                    }
                    if (password == "")
                    {
                        Response.Write("<script>alert('请输入要修改的密码!')</script>");
                        return;
                    }
                    conn.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "Select COUNT(*) FROM USERINFO Where USERNAME ='" + username + "'";
                    int i = (int)cmd.ExecuteScalar();
                    if (i < 1)
                    {
                        Response.Write("<script>alert('修改的用户名不存在!')</script>");
                        return;
                    }
                    cmd.CommandText = "Update USERINFO SET PASSWORD ='" + password + "' Where USERNAME='" + username + "'";
                    // cmd.ExecuteReader();
                    SqlDataReader reader = cmd.ExecuteReader();
                    this.GridView1.DataSource = reader;
                    this.GridView1.DataBind();
                    reader.Close();
                    Response.Write("<script>alert('修改成功!')</script>");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }
        //#############################登录开始################################
        protected void Button1_Click(object sender, EventArgs e)
        {
            this.logininfo(this.TextBox1.Text, this.TextBox2.Text);
        }
        public void logininfo(string username, string password)
        {
        using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                if(username=="" || password=="")
                {
                    Response.Write("<script>alert('用户名密码不能为空!')</script>");
                    return;
                }
                cmd.CommandText = "Select * FROM USERINFO Where USERNAME='" + username + "' AND PASSWORD='" + password + "'";
                SqlDataReader reader = cmd.ExecuteReader();
                using(reader)
                {
                    string name = string.Empty;
                    string pwd = string.Empty;
                    while(reader.Read())
                    {
                        name = reader["USERNAME"].ToString();
                        pwd = reader["PASSWORD"].ToString();
                    }
                    if (name == username || pwd == password)
                    {
                        Response.Cookies["names"].Value = username;
                        Session["admins"] = username;
                        Session["times"] = DateTime.Now.ToString();
                        Label1.Visible = true;
                        Label1.Text = "LOGIN TIME:"+Session["times"].ToString();
                        Label1.Text += "USER:" + Session["admins"].ToString();
                        Response.Write("Cookies:" + Response.Cookies["names"].Value.ToString());
                        Button7.Visible = true;
                        Response.Write("<script>alert('登录成功!')</script>");
                    }
                    else
                    {
                        Response.Write("<script>alert('账号或者密码错误!')</script>");

                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        }

        protected void Button7_Click1(object sender, EventArgs e)
        {
            Response.Cookies["names"].Expires = DateTime.Now.AddDays(-1);
            Session.RemoveAll();
            TextBox1.Text = "";
            TextBox2.Text = "";
            Response.Write("<script>alert('退出成功!');location.href='default.aspx';</script>");
        }

        protected void Button8_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
        }
    }
}



[本日志由 月神 于 2011-12-12 01:30 AM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: connection command dataread DataSource session cookies
相关日志:
评论: 2 | 引用: 0 | 查看次数: -
回复回复月神[2011-12-12 02:26 AM | del]
以上代码仅仅作为示例学习,不要用于正式开发中去!
提醒:如登录系统中常用的sql注入漏洞,以上示例中虽然得到了过滤,但在实际开发中仍然不推荐这样使用,下面为正常开发中常用的方法
//  cmd.CommandText = "Select * FROM USERINFO Where USERNAME='" + username + "' AND PASSWORD='" + password + "'";
                cmd.CommandText = "Select * FROM USERINFO Where USERNAME=@name AND PASSWORD=@pwd";
                cmd.Parameters.Add(new SqlParameter("name",username));
                cmd.Parameters.Add(new SqlParameter("pwd",password));
回复回复月神[2011-12-12 01:34 AM | del]
本示例中还包含了对象参数的传递、调用,cookies读取,过期设置,session对象创建移除以及GridView控件绑定数据源,读取数据源数据等等知识点。
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.