1. 程式人生 > >EasyUI結合Sqlserver資料庫實現一個分頁顯示資料

EasyUI結合Sqlserver資料庫實現一個分頁顯示資料

EasyUI大多數會被用在做後臺的美化,以及資料的展示。

今天是六一兒童節,祝各位程式設計師們,兒童節快樂哈!

話不多說,我們開始正題。

先來看看我們這個小案例的專案目錄:

App_Data中的四個檔案是博主為了方便檢視專案把他放在一起。

步驟一:我們編寫了資料庫指令碼.sql檔案,在sqlserver執行即可生產海量資料

use master
go
if db_id('EasyUIPageData') is not null
	drop database EasyUIPageData
go

create database EasyUIPageData
go

use EasyUIPageData
go

create table tbInfors 
(
  id int identity primary key,  --主鍵
  author varchar(256),          --作者
  title varchar(256),           --標題
  addTime datetime              --新增時間
)
go

declare @i int=1
declare @author varchar(200)
declare @title varchar(200)
while @i< 49999
begin
  set @title='第'+CONVERT(varchar,@i)+'條資料標題';
  set @author='第'+CONVERT(varchar,@i)+'個作者';
  insert into tbInfors (author,title,Addtime)
  values (@author,@title, getDate())
  set @i = @i + 1;
end
go

select count(*) from tbInfors
--truncate table T_Product

步驟二:我們編寫相應的分頁儲存過程.sql,並執行

CREATE PROCEDURE [dbo].[GetDatasByPaging] 
	@pagesize int =10,--每頁行數
    @pageindex int =0,--第幾頁
    @tablename varchar(200),--資料篩選的表或表的聯合
    @orderstr varchar(100),--排序表示式
    @pk  varchar(20),--主鍵
    @columns varchar(600),--選擇的列
    @filterstr varchar(200) --篩選條件
AS
BEGIN

	SET NOCOUNT ON
    Declare @sql nvarchar(1000) 
    set @sql='select  top '+ cast(@pagesize as VARCHAR(4))+ '  '+ @columns +' 
      from '
[email protected]
+' where('+ @pk +' not in(select top '+ cast(@pageSize*@pageIndex as VARCHAR(20))+' '+ @pk +' from '+ @tablename +' where '+ @filterstr+' order by '+ @orderstr +')) and '+ @filterstr +' order by '+ @orderstr print @sql execute(@sql) SET NOCOUNT OFF END

資料庫裡的目錄如下:


步驟三:如下

我這裡用的是三層,各層之間的引用如下:

Models:基礎層;

DAL:資料訪問層,需引用Models;

BLL:業務邏輯層,需引用Models,DAL;

Web:頁面展示層,需引用Models,BLL;

新增好三層以及各層的引用後,讓我們完成各層的操作。

EasyUI_Models裡面新增實體類Info.cs

using System;

namespace EasyUI_Models
{
    /// <summary>
    /// 資訊實體類
    /// </summary>
    public class Info
    {
        /// <summary>
        /// 編號
        /// </summary>
        public int id { get; set; }
        /// <summary>
        /// 作者
        /// </summary>
        public string author { get; set; }
        /// <summary>
        /// 標題
        /// </summary>
        public string title { get; set; }
        /// <summary>
        /// 新增時間
        /// </summary>
        public DateTime addTime { get; set; }
    }
}

EasyUI_DAL裡需新增DBHelper.cs和InfoDAL.cs

DBHelper.cs

using System.Configuration;//需引用
using System.Data;
using System.Data.SqlClient;

namespace MeiTao.DAL
{
    public class DBHelper
    {
        /// <summary>
        /// 靜態配置檔案讀取連結字串,在EasyUI_Web中的Web.config中設定
        /// </summary>
        private static string DBConnectString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        private static SqlConnection conn;
        private static SqlDataAdapter da;
        private static SqlCommand cmd;
        private static DBHelper dBHelper;

        public DBHelper()
        {
            conn = new SqlConnection(DBConnectString);
        }
        /// <summary>
        /// 例項化DBHelper物件
        /// </summary>
        /// <returns></returns>
        public static DBHelper Instance()
        {
            if (dBHelper == null)
            {
                dBHelper = new DBHelper();
            }
            return dBHelper;
        }
        /// <summary>
        /// 開啟資料庫連線
        /// </summary>
        void DBOpen()
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
        }
        /// <summary>
        /// 關閉資料庫連線
        /// </summary>
        void DBClose()
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
        /// <summary>
        /// 執行SQL語句獲取資料集
        /// </summary>
        /// <param name="sql">sql語句</param>
        /// <returns>DataTable資料集</returns>
        public DataTable GetDataTableBySql(string sql)
        {
            DBOpen();
            DataTable dt = new DataTable();
            da = new SqlDataAdapter(sql, conn);
            try
            {
                da.Fill(dt);
                return dt;
            }
            catch
            {
                return null;
            }
            finally
            {
                DBClose();
            }
        }
        /// <summary>
        /// 執行SQL語句
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>是否執行成功</returns>
        public bool ExcuteSql(string sql)
        {
            DBOpen();
            cmd = new SqlCommand(sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                DBClose();
            }
        }
        /// <summary>
        /// 執行儲存過程
        /// </summary>
        /// <param name="proName">儲存過程名稱</param>
        /// <param name="paras">儲存過程引數</param>
        /// <returns>是否執行成功</returns>
        public bool ExcuteProcedure(string proName, SqlParameter[] paras)
        {
            DBOpen();
            cmd = new SqlCommand(proName, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            for (int i = 0; i < paras.Length; i++)
            {
                cmd.Parameters.Add(paras[i]);
            }
            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                DBClose();
            }

        }
        /// <summary>
        /// 執行儲存過程獲得資料集
        /// </summary>
        /// <param name="proName">儲存過程名</param>
        /// <param name="paras">儲存過程引數</param>
        /// <returns>DataTable資料集</returns>
        public DataTable GetDataTableByProcedure(string proName, SqlParameter[] paras)
        {
            DBOpen();
            cmd = new SqlCommand(proName, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            for (int i = 0; i < paras.Length; i++)
            {
                cmd.Parameters.Add(paras[i]);
            }
            try
            {
                da.Fill(dt);
                return dt;
            }
            catch
            {
                return null;
            }
            finally
            {
                DBClose();
            }

        }

    }
}
EasyUI_Web層Web.config檔案新增如下配置
 <!--配置連線字串-->
  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="server=.;database=EasyUIPageData;uid=sa;pwd=123456;"/>
  </connectionStrings>

InfoDAL.cs

using EasyUI_Models;
using MeiTao.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace EasyUI_DAL
{
    public class InfoDAL
    {

        #region 方法一:使用儲存過程,需要先查詢記錄行數,再查詢表中資料
        /// <summary>
        /// 分頁查詢表中資料
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns>分頁查詢結果</returns>
        public static List<Info> SelectByPaging(int pageSize, int pageIndex)
        {
            string proName = "GetDatasByPaging";
            SqlParameter[] paras = {
                new SqlParameter("@pagesize",pageSize),
                new SqlParameter("@pageindex",pageIndex),
                new SqlParameter("@tablename","tbInfors"),
                new SqlParameter("@orderstr","id asc"),
                new SqlParameter("@pk","id"),
                new SqlParameter("@columns","*"),
                new SqlParameter("@filterstr","1=1")
            };

            DataTable dt = DBHelper.Instance().GetDataTableByProcedure(proName, paras);

            List<Info> list = new List<Info>();

            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Info info = new Info
                    {
                        id = int.Parse(dr["id"].ToString()),
                        author = dr["author"].ToString(),
                        title = dr["title"].ToString(),
                        addTime = DateTime.Parse(dr["addTime"].ToString())
                    };
                    list.Add(info);
                }
            }
            return list;
        }

        /// <summary>
        /// 獲得所有記錄行數
        /// </summary>
        /// <returns></returns>
        public static int SeletTotalCount()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select count(1) from tbInfors");
            DataTable dt = DBHelper.Instance().GetDataTableBySql(sb.ToString());
            int count = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                count = int.Parse(dt.Rows[0][0].ToString());
            }
            return count;
        }
        #endregion

        #region 方法二:使用泛型儲存資料庫裡所有資料
        /// <summary>
        /// 查詢資料庫裡所有資料
        /// </summary>
        /// <returns></returns>
        public static List<Info> SelectAllData()
        {
            //string sql = "select * from tbInfors";
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from tbInfors");
            
            DataTable dt = DBHelper.Instance().GetDataTableBySql(sb.ToString());

            List<Info> list = new List<Info>();

            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Info info = new Info
                    {
                        id = int.Parse(dr["id"].ToString()),
                        author = dr["author"].ToString(),
                        title = dr["title"].ToString(),
                        addTime = DateTime.Parse(dr["addTime"].ToString())
                    };
                    list.Add(info);
                }
            }
            return list;
        }
        #endregion

    }
}

EasyUI_BLL需新增InfoBLL.cs

InfoBLL.cs

using EasyUI_DAL;
using EasyUI_Models;
using System.Collections.Generic;
namespace EasyUI_BLL
{
    public class InfoBLL
    {
        #region 方法一
        public static List<Info> GetByPaging(int pageSize, int pageIndex)
        {
            return InfoDAL.SelectByPaging(pageSize, pageIndex);
        }


        public static int GetTotalCount()
        {
            return InfoDAL.SeletTotalCount();
        }
        #endregion

        #region 方法二
        public static List<Info> GetAllData()
        {
            return InfoDAL.SelectAllData();
        }
        #endregion

    }
}

EasyUI_Web中先匯入EasyUI資源:

新增傳遞資料頁面Data.aspx,並刪除除第一行的程式碼。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Data.aspx.cs" Inherits="EasyUI_Web.Data" %>

在該頁面右鍵檢視程式碼,寫入下面後臺程式碼:

其中要匯入第三方外掛Newtonsoft.json我們可以去百度裡下載。

using EasyUI_BLL;
using EasyUI_Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;//方法二,用Skip,Take

namespace EasyUI_Web
{
    public partial class Data : System.Web.UI.Page
    {
        /*
         * 二種查詢方法各有各的好處,
         * 方法一:使用了儲存過程,使用者先將資料從想要的部分資料獲取出來,下一次想要檢視其它資料,還得重新從資料庫查一遍。這樣做效率高,效能比較好。
         * 方法二:一次性查詢資料庫所有的資料,在我們需要顯示相應資料的時候,直接拿出來用,不要再經過資料庫,比較靈活但是,資料量過大的時候,初次載入會比較慢。
         * 推薦使用第一種方法
         */
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                //GetData();//方法一
                SimpleGetData();//方法二
            }
        }
        private void GetData()
        {
            //獲取記錄總數
            int totalCount = InfoBLL.GetTotalCount();
            //通過Request 根據分頁引數,來獲得分頁資料
            //1.每頁顯示N條記錄
            int rows = int.Parse(Request["rows"]);
            //2.當前是第X頁
            int page = int.Parse(Request["page"]);   
            //3.獲得分頁記錄
            List<Info> list = InfoBLL.GetByPaging(rows, page - 1);
            //4.返回Json格式的資料給easyui的DataGrid元件
            //這裡的  new {total = totalCount,rows = list}是匿名集合,不能用變數接收。
            Response.Write(JsonConvert.SerializeObject(
                    new {
                            total =totalCount,
                            rows =list
                    }));
        }

        private void SimpleGetData()
        {
            //1.每頁顯示N條記錄
            int rows = int.Parse(Request["rows"]);
            //2.當前是第X頁
            int page = int.Parse(Request["page"]);
            List<Info> ins = InfoBLL.GetAllData();
            //new { total = ins.Count, rows = ins.Skip((page - 1) * rows).Take(rows) }為匿名集合,不能用變數來接收
            Response.Write(JsonConvert.SerializeObject(
                new {
                        total = ins.Count,
                        rows = ins.Skip((page - 1) * rows).Take(rows)
                        //(page-1)是因為,easyui裡page預設從0開始
                        //Skip:獲取所有資料,
                        //Take:獲取想要的資料
                }));
        }
    }
}

再建立一個ShowData.html,該頁面使用easyui的datagrid元件來接收並顯示資料

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>分頁顯示資料</title>
    <link href="EasyUI/themes/black/easyui.css" rel="stylesheet" />
    <link href="EasyUI/themes/icon.css" rel="stylesheet" />
    <script src="EasyUI/jquery.min.js"></script>
    <script src="EasyUI/jquery.easyui.min.js"></script>
    <script src="EasyUI/locale/easyui-lang-zh_CN.js"></script>
    <script>
        $(function () {
            $("#dg").datagrid({
                fit: true,//自動填充
                striped: true,//斑馬線
                rownumbers: true,//行編號
                fitColumns: true, //自動填充列            
                url: 'Data.aspx',//遠端載入資料
                pagination: true,//顯示分頁欄             
                columns: [[                   
                    { field: 'id', align: 'center', title: '編號',width: 80 },
                    { field: 'author', align: 'center', title: '作者', width: 80 },
                    { field: 'title', align: 'center', title: '標題', width: 80 },
                    { field: 'addTime', align: 'center', title: '新增時間', width: 80 }
                        ]]
            });
        });
    </script>
</head>
<body>
    <table id="dg"></table>
</body>
</html>

最後,我們看下最終的效果:


大功告成!

後面會不定時更新資料的增刪改系列操作!

謝謝大家支援!

相關推薦

EasyUI結合Sqlserver資料庫實現一個顯示資料

EasyUI大多數會被用在做後臺的美化,以及資料的展示。今天是六一兒童節,祝各位程式設計師們,兒童節快樂哈!話不多說,我們開始正題。先來看看我們這個小案例的專案目錄:App_Data中的四個檔案是博主為了方便檢視專案把他放在一起。步驟一:我們編寫了資料庫指令碼.sql檔案,在

例項:建立一個表格,顯示資料(MongoDB資料庫儲存),功能:實現增刪改查

需求:建立一個表格,分頁顯示資料,功能:實現增刪改查 效果圖: 自動建立一個專案 命令列: express mongodb-demo --view=ejs cd mongodb-demo npm install npm install mongodb --save npm sta

Springboot+easyui實現資料庫前臺資訊顯示

資料庫中的資訊在前臺的分頁顯示.        為什麼要進行要分頁?是為了在前臺頁面中不採用滾動條的形式看起來更加的美觀.同時如果不採用分頁的形式,如果資料量較大的話,瀏覽器的請求會特別的耗費時間,可

vue實現一個元件

Vue.component("page",{ template:"#page", data:function(){ return{ current:1, showItem:5, al

mybatis實現MySQL顯示

SQL語句 select * from table_name limit startNum,Size 這句話的意思是從第startNum個數據開始(索引從0開始),總共顯示Size個。 注意,當為第一頁時,startNum為0,當為第二頁時,startNum為p

Django前端實現列表顯示

有兩種方案: 一、使用Django的分頁外掛 詳細步驟參考http://blog.csdn.net/fighter_yy/article/details/41308277 缺點:django1.6版本之前無法使用 二、使用datatable(功能更強大,推薦)

Android ListView實現顯示資料

當有大量的資料需要載入到ListView的Adapter中時,全部一次性載入,通常會非常耗時,這將嚴重影響使用者的體驗性和流暢性,而分頁載入則會優化載入的速度,先暫時顯示一頁能夠顯示的資料項,在拖動到最下方時或點選了“顯示更多”按鈕時,再載入部分(需要自己定義每次顯示多少)

ssm框架整合入門系列——查詢-顯示資料

ssm框架整合入門系列——查詢-分頁顯示資料(pageHelper的使用) 查詢也就是顯示操作,在該專案下具體表現為: 訪問index.jsp頁面 index.jsp頁面傳送出查詢員工列表請求 EmployeeController 來接受請求,查出員工資料 來到list.jsp頁面進

Spring boot顯示資料(1)

spring boot分頁顯示資料(1) 記錄一下~ 我們從簡入繁,先使用一種通過頁面重新整理來實現分頁資料展示的方法~ 下面是一個簡單的栗子 使用工具:spring-data-jpa,thymeleaf 實體類: 實體類中不要忘記定義空的構造方法哦~

JSP頁面顯示資料

一、原始碼(這裡以一個Java web的留言板專案為例): 1.Dao層操作資料庫的方法(MessageDao.java) 設定每頁顯示的最大留言條數: private final int MAX_SIZE = 2; // 每頁顯示的最大留言數 從資料庫讀取留言的總

Web顯示資料

這個是基於MVC框架寫的。 首先對資料庫進行封裝處理 public class DataBase { static String driver = "com.mysql.jdbc.Driver"; static String url =

JSP顯示資料

最近在做一個小程式,用到了JSP的分頁。雖然只是最簡單的分頁,但是還是花了我不少時間。這看似簡單的功能,實現起來還是稍微有點麻煩。實現分頁功能,需要知道資料的總個數,每頁應該有多少條資料,以及當前頁碼。假如總共有300條資料,每頁20條,那麼應該就有15頁;假設

dede 列表標籤 (也就是顯示資料)

<h2>list 列表資料標籤 infolen 不能控制 description 所以用infos</h2> {dede:list pagesize='10' infolen=

Javaweb中結合mysql資料庫實現功能

Javaweb分頁技術實現 分頁技術就是通過SQL語句(如下)來獲取資料,具體實現看下面程式碼 //分頁查詢語句 select * from 表名 where limit page , count; 和 //獲取表中的總資料,確定頁數 select count(*) f

JSP實現 留言板 顯示,新留言顯示在第一個~

date() sdf style string hid pre || lan pat 頁面效果圖: 留言Servlet-----MessageServlet package cn.MuJH.newsManager.servlet; import java.io.

Koa2學習之旅----結合 jqPaginator實現列表

1.下載jqPaginator.js  放在靜態目錄裡面 2、在需要分頁的地方引入jqPaginator.js  3、在需要分頁的地方加個空div     <div id="page" class="pagination"></

SpringBoot+Easyui+pagehelper實現功能

1.首先引入jar包 <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <ve

Bootstrap結合angularjs顯示,實現當前選中居中效果

bosfore_app.controller("ctrlRead", ['$scope', '$http', function($scope, $http) { $scope.currentPage = 1; //當前頁 $scope.pageSize = 4; /

結合Tab,ViewPager,Fragment實現簡單滑動

在APP設計當中,使用ViewPager和Fragment來實現分頁滑動並不少見,該設計可以利用少量的空間來實現多內容的展示。效果圖如下: 以下是實現該功能的程式碼: MainActivity public class MainActivity e

jsp實現顯示資訊(資料庫、EL表示式、連線池)

一、準備工作 1.1在mysql資料庫中你建立學生的表 1.2細節: 1.2.0. 先匯入musql的jar包 1.2.1. 性別一般用列舉型 1.2.2. 要將錶轉儲sql檔案,放在web專案額web-info下面