用WebService实现对数据库进行操作(添加+删除+修改)

来源:互联网 发布:淘宝店女装退货率30 编辑:程序博客网 时间:2024/04/30 15:14
表为User,字段有 编号: int id,用户名:string UserName,密码:string UserPwd
   /// <summary>
    /// 添加      
    /// </summary>
    /// <param name="name">用户名</param>
    /// <param name="pwd">密码</param>
    /// <returns></returns>
    [WebMethod]
    public int Add(string name,string pwd)
    {
        SqlConnection conn = new SqlConnection("连接字符串");
        conn.Open();
        string sql = "intsert into User (UserName,UsersPwd) values(@UserName,@UsersPwd)";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlParameter parn = new SqlParameter("@UserName", name);
        cmd.Parameters.Add(parn);
        SqlParameter parp = new SqlParameter("@UsersPwd", pwd);
        cmd.Parameters.Add(parp);
        int result = cmd.ExecuteNonQuery();
        conn.Close();
        cmd.Dispose();
        return result;
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="name">用户名</param>
    /// <param name="pwd">密码</param>
    /// <param name="id">编号</param>
    /// <returns></returns>
    [WebMethod]
    public int Update(string name, string pwd, int id)
    {
        SqlConnection conn = new SqlConnection("连接字符串");
        conn.Open();
        string sql = "update User set UserName=@UserName,UsersPwd=@UsersPwd where id=@id";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlParameter parn = new SqlParameter("@UserName", name);
        cmd.Parameters.Add(parn);
        SqlParameter parp = new SqlParameter("@UsersPwd", pwd);
        cmd.Parameters.Add(parp);
        SqlParameter pari = new SqlParameter("@id", id);
        cmd.Parameters.Add(pari);
        int result = cmd.ExecuteNonQuery();
        conn.Close();
        cmd.Dispose();
        return result;
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="id">编号</param>
    /// <returns></returns>
    [WebMethod]
    public int Delete(int id)
    {
        SqlConnection conn = new SqlConnection("连接字符串");
        conn.Open();
        string sql = "delete from User where id=@id";
        SqlCommand cmd = new SqlCommand(sql, conn);        
        SqlParameter pari = new SqlParameter("@id", id);
        cmd.Parameters.Add(pari);
        int result = cmd.ExecuteNonQuery();
        conn.Close();
        cmd.Dispose();
        return result;
    }
原创粉丝点击