惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 澜心

面向对象语言的new操作 - 澜心 javascript复习一 JavaScript的面向对象 C#在word中插入上标的问题 新建SSIS项目失败或者在SSIS项目中新建包失败 往消息队列传数据的存储过程 C#泛型学习 空气污染指数的计算公式是什么?(API) 行列转换 - 澜心 - 博客园 数据中心和数据仓库,在信息化建设中有何作用? - 澜心 【求助】Vs2005当前不能命中断点 自动加载用户控件问题【找到部分原因】 【讨论】程序员的发展道路如何规划,欢迎大家加入讨论 sql常用函数汇总 网站配色方案学习 用例指南 - 澜心 用例 UseCase 系统分析员基本功 网站安装步骤 sqlserver2000下载地址 SQLServer2000安装图解
简单数据库操作
澜心 · 2008-03-06 · via 博客园 - 澜心

简单数据库操作

2008-03-06 09:13  澜心  阅读(281)  评论()    收藏  举报

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Logic;


public partial class edit : System.Web.UI.Page
{
    
private string ID
    
{
        
get
        
{
            
if (Request["ID"!= null)
                
return Request["ID"].ToString();
            
else
                
return "";
        }

    }

    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
        
{
            
if (ID.Length > 0)
            
{
                Users users 
= new Users();
                users.LoadMe(
int.Parse(ID));
                txtName.Text 
= users.Name;
                txtPassword.Text 
= users.Password;
            }

        }

    }

    
protected void TextBox1_TextChanged(object sender, EventArgs e)
    
{

    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        Users users 
= new Users();
        users.Name 
= txtName.Text;
        users.Password 
= txtPassword.Text;
        
if (ID.Length > 0)
        
{
            users.ID 
= Convert.ToInt32(ID);
            users.Update();
            Page.RegisterStartupScript(
"ss""<script>alert('修改成功!');window.opener.__doPostBack('Button1','');window.close();</script>");

        }

        
else
        
{
            users.Insert();
            Page.RegisterStartupScript(
"ss""<script>alert('添加成功!');window.opener.__doPostBack('Button1','');window.close();</script>");
        }


        
//Page.RegisterStartupScript("sfsfsdf","<script>alert('添加成功!');</script>");
    }

}

数据层类:主要用于数据访问

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
/// <summary>
/// DataAccess 的摘要说明
/// </summary>

public class DataAccess
{

    
string connectionStr = "";
    SqlConnection conn;
    SqlCommand comm;
    SqlDataAdapter sqlDataAdapter;
    
public DataAccess()
    
{
        connectionStr 
= System.Configuration.ConfigurationSettings.AppSettings["connnectionstring"];
        conn 
= new SqlConnection(connectionStr);
    }


    
/// <summary>
    
/// 执行命令,返回受影响的行数
    
/// </summary>
    
/// <param name="sql"></param>
    
/// <returns></returns>

    public int ExecuteNoQuery(string sql)
    
{
        conn.Open();
        
//comm = new SqlCommand();
        
//comm.Connection = conn;
        
//comm.CommandText = sql;

        comm 
= new SqlCommand(sql, conn);
        
int result = comm.ExecuteNonQuery();
        comm.Dispose();
        conn.Close();
        
return result;
    
    }



    
/// <summary>
    
/// 返回已经填充数据的DataSet
    
/// </summary>
    
/// <param name="sql"></param>
    
/// <returns></returns>

    public DataSet ExecuteDataSet(string sql)
    
{
        conn.Open();
        comm 
= new SqlCommand(sql, conn);
        sqlDataAdapter 
= new SqlDataAdapter(comm);
        DataSet ds 
= new DataSet();
        sqlDataAdapter.Fill(ds);
        conn.Close();
        
return ds;
    }

    
public string ExecuteScalar(string sql)
    
{
        conn.Open();
        
//comm = new SqlCommand();
        
//comm.Connection = conn;
        
//comm.CommandText = sql;

        comm 
= new SqlCommand(sql, conn);
        
object obj = comm.ExecuteScalar();
        comm.Dispose();
        conn.Close();
        
return obj.ToString();
    }

}

逻辑层 主要是实体类

using System;
using System.Data;
using System.Collections.Generic;
using System.Text;

namespace Logic
{
    
public class Users
    
{
        DataAccess da 
= new DataAccess();
       
        
属性,分别对应数据库中的字段  


        
/// <summary>
        
/// 根据主键,去数据库中查询,并用查询到的数据填充该类
        
/// </summary>
        
/// <param name="ID"></param>

        public void LoadMe(int ID)
        
{
            
string sql = string.Format("select * from users where 1=1 and ID = {0}", ID);
            DataSet ds 
= da.ExecuteDataSet(sql);
            DataTable dt 
= ds.Tables[0];
            DataRow row 
= dt.Rows[0];
            m_Name 
= row["name"].ToString();
            m_Password 
= row["password"].ToString();
        }


        
public bool Insert()
        
{
            
string sql = string.Format("insert into users(name,password) values('{0}','{1}')",m_Name,m_Password);
            
int result = da.ExecuteNoQuery(sql);
            
return (result == 1);          
        }


        
public bool Update()
        
{
            
string sql = string.Format("update users set name = '{0}',password = '{1}' where 1=1 and ID = {2}", m_Name, m_Password,m_ID);
            
int result = da.ExecuteNoQuery(sql);
            
return (result == 1);
        }


        
public bool Delete()
        
{
            
string sql = string.Format(" delete from users where 1=1 and ID = {0}", m_ID);
            
int result = da.ExecuteNoQuery(sql);
            
return (result == 1);
        }


        
public Users()
        

        
        }


        
public bool Login(string name, string password)
        
{
            StringBuilder sb 
= new StringBuilder();
            sb.Append(
"select count(*) from users where 1=1 ");
            sb.AppendFormat(
" and name = '{0}' and password = '{1}' ", name,password);
            
string result = da.ExecuteScalar(sb.ToString());
            
return (result == "1");
        }

    }

}

List页面

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//using Data;
using Logic;

public partial class List : System.Web.UI.Page
{
    DataAccess da 
= new DataAccess();
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
///第一次加载的时候执行,点击按钮等请求的时候不再执行该段代码
        if (!Page.IsPostBack)
        
{

            BindGridView();
        }

    }


    
public void BindGridView()
    
{
        
string sql = "select * from users ";
        DataSet ds 
= da.ExecuteDataSet(sql);
        GridView1.DataSource 
= ds;
        GridView1.DataBind();
    }



    
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    
{
        
    }

    
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    
{
        
string cmd = e.CommandName.ToString();
        
string ID = e.CommandArgument.ToString();
        Users users 
= new Users();
        users.ID 
= int.Parse(ID);
        users.Delete();
        BindGridView();
    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        BindGridView();
    }

    
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow)
        
{
            LinkButton deleteBtn 
= (LinkButton)e.Row.FindControl("LbDeleteButton");
            deleteBtn.Attributes.Add(
"onclick""return confirm('确定删除吗?');");
        }

    }

}

编辑页面