首页 > 代码库 > asp.net LINQ连接数据库SQL执行数据的增加、修改、删除、查询操作

asp.net LINQ连接数据库SQL执行数据的增加、修改、删除、查询操作

查询数据库中的数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataClassesDataContext lqDB = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["db2016ConnectionString"].ConnectionString.ToString());
        var result = from r in lqDB.news
                     where r.id > 0
                     select r;
        GridView1.DataSource = result;
        GridView1.DataBind(); 
    }
}

向数据库中添加数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        LinqDBDataContext lqDB = new LinqDBDataContext(ConfigurationManager.ConnectionStrings["db2016ConnectionString"].ConnectionString.ToString());
        news info = new news();
        info.content = TextBox1.Text;
        lqDB.news.InsertOnSubmit(info);
        lqDB.SubmitChanges();
        Page.ClientScript.RegisterStartupScript(GetType(), "", "alert(‘发表成功‘);location.href=http://www.mamicode.com/‘Default.aspx‘", true);
    }
}

修改数据

  protected void Page_Load(object sender, EventArgs e)
    {
        LinqDBDataContext lqDB = new LinqDBDataContext(ConfigurationManager.ConnectionStrings["db2016ConnectionString"].ConnectionString.ToString());

        var result = from r in lqDB.news
                     where r.id == 1
                     select r;
        foreach (news info1 in result)
        {
            info1.content = "没有做不到的事情,我是最棒的";
        }
        lqDB.SubmitChanges();
    }

删除数据

LinqDBDataContext lqDB = new LinqDBDataContext(ConfigurationManager.ConnectionStrings["db2016ConnectionString"].ConnectionString.ToString());

        var result = from r in lqDB.news
                     where r.id == 1
                     select r;
        lqDB.news.DeleteAllOnSubmit(result);
        lqDB.SubmitChanges();

 

asp.net LINQ连接数据库SQL执行数据的增加、修改、删除、查询操作