搜文章
推荐 原创 视频 Java开发 iOS开发 前端开发 JavaScript开发 Android开发 PHP开发 数据库 开发工具 Python开发 Kotlin开发 Ruby开发 .NET开发 服务器运维 开放平台 架构师 大数据 云计算 人工智能 开发语言 其它开发
Lambda在线 > 走出一条属于自己的路 > 数据库数据实时显示

数据库数据实时显示

走出一条属于自己的路 2018-06-30

1、准备工作

     安装SignalR     工具箱------扩展和更新----NUGET Package

                              NUGET工具包管理----管理解决方案的包

2、主要用途

      数据库数据更新时,前端网页自动更新

3、APP_Start   创建一个类   类名startup1

    

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApplication1.App_Start.Startup1))]

namespace WebApplication1.App_Start
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            //注册signalr/hubs
            app.MapSignalR();
        }
    }
}

4、设置webconfig

      <connectionStrings>
    <add name="InsusSqlConnectionString"
         connectionString="Data Source=.;Initial Catalog=Test1.0;User ID=sa;Password=123456" providerName="System.Data.SqlClient"/>
  </connectionStrings>


5、Global.asax.cs 添加方法

     

 protected void Application_Start()
        {
           
            SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings["InsusSqlConnectionString"].ConnectionString);

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
           
        }

        protected void Application_End() {
            SqlDependency.Stop(System.Configuration.ConfigurationManager.ConnectionStrings["InsusSqlConnectionString"].ConnectionString);
        }


6、创建models    tableb

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class TableB
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Z { get; set; }
    }
}


7、数据库启动SQL SERVER SERVICE BROKER

  SELECT is_broker_enabled FROM sys.databases WHERE name = 'Test1.0'
ALTER DATABASE [Test1.0] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [Test1.0] SET ENABLE_BROKER;


8、创建SignalR目录   添加Hub类

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;


namespace WebApplication1.SignalR
{
    [HubName("tableBService")]
    public class TableBHub:Hub
    {
        [HubMethodName("show")]
        public static void Show()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TableBHub>();
            // context.Clients.All.displayDates();
            context.Clients.All.displayStatus();
        }
    }
}



9、实现数据库获取数据,当数据库发生变化时,触发事件

     

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication1.Models;
using System.Data.SqlClient;
using WebApplication1.DataBases;
using System.Data;
using WebApplication1.SignalR;


namespace WebApplication1.Entities
{
    public class TableBEntity
    {
        private static string _connStr;
         public IEnumerable<TableB> GetData()
         {

             using (var sqlConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["InsusSqlConnectionString"].ConnectionString))
             {
                 //string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
                 sqlConnection.Open();
                 using (SqlCommand sqlCommand = new SqlCommand($"SELECT [X],[Y],[Z] FROM [Test1.0].[dbo].[ff]", sqlConnection))
                 {
                     sqlCommand.Notification = null;
                     //SqlDependency.Start(InsusSqlConnectionString);
                     SqlDependency dependency = new SqlDependency(sqlCommand);
                    //dependency.OnChange += new OnChangeEventHandler(dependency_Onchange);
                    dependency.OnChange += dependency_Onchange;
                    if (sqlConnection.State == ConnectionState.Closed)
                         sqlConnection.Open();
                     using (var reader = sqlCommand.ExecuteReader())
                     {
                        while (reader.Read())
                        {
                            return reader.Cast<IDataRecord>().Select(a => new TableB()
                            {
                                X = Convert.ToInt16(a["X"]),
                                Y = Convert.ToInt16(a["Y"]),
                                Z = Convert.ToInt16(a["Z"]),
                             }).ToList();
                        }
                       
                     }
                 }
             }
            return null;
         }

        public void dependency_Onchange(object sender, SqlNotificationEventArgs e)
        {
            TableBHub.Show();
        }

    }
}


10、创建控制器

      

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Entities;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

    
       [HttpPost]
        public JsonResult Get()
        {
            TableBEntity tab = new TableBEntity();
            var model = tab.GetData();
            return Json(model, JsonRequestBehavior.AllowGet);
        }
    }
}



11、前端视图

@{
    ViewBag.Title = "实时显示";
}

@{
    Layout = null;
}}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width-device-width" />
    <title>SignalR</title>
    <script src=@Url.Content("~/Scripts/jquery-1.10.2.js") type="text/javascript"></script>
    <script src=@Url.Content("~/Scripts/jquery.signalR-2.2.3.min.js") type="text/javascript"></script>
    <script src=@Url.Content("~/signalr/hubs") type="text/javascript"></script>
    <script src=@Url.Content("~/signalr/js") type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.tableBService;
            proxy.client.displayStatus = function () {
           // proxy.client.displayDates = function () {
                getData();
            }
            $.connection.hub.start();
            getData();
            $.connection.hub.start().done(function () {
                getData();
            });
        });

        function getData() {
            $.ajax({
                type: 'POST',
                url: '/Home/Get',
                dataType: "json",
                success: function (data) {
                    var tbody1 = $('#tbody1');
                    tbody1.empty();
                    $.each(data, function (i, item) {
                        tbody1.append("<tr>" +
                            "<td>" + item.X + "</td>" +
                            "<td>" + item.Y + "</td>" +
                            "<td>" + item.Z + "</td>" +
                            "</tr>");
                    });
                }
            });
        }
    </script>
</head>
<body>
    <table>
        <tr>
            <th>X</th>
            <th>Y</th>
            <th>Z</th>
        </tr>
        <tbody id="tbody1"></tbody>
    </table>
</body>
</html>




版权声明:本站内容全部来自于腾讯微信公众号,属第三方自助推荐收录。《数据库数据实时显示》的版权归原作者「走出一条属于自己的路」所有,文章言论观点不代表Lambda在线的观点, Lambda在线不承担任何法律责任。如需删除可联系QQ:516101458

文章来源: 阅读原文

相关阅读

关注走出一条属于自己的路微信公众号

走出一条属于自己的路微信公众号:gh_585a9a8a6262

走出一条属于自己的路

手机扫描上方二维码即可关注走出一条属于自己的路微信公众号

走出一条属于自己的路最新文章

精品公众号随机推荐