搜尋
首頁資料庫mysql教程nosql数据库STSDB的一般性使用

接着上一篇这里罗列下STSDB的一般性使用 以下内容基于stsdb4.dll(4.0.3.0版本)库(百度分享资源:http://pan.baidu.com/s/1jGxHE3k),截止本文发布,官方最新版本是4.0.5.0,官方地址:http://stsdb.com/ using System;using System.Collections.Generic;

接着上一篇这里罗列下STSDB的一般性使用

以下内容基于stsdb4.dll(4.0.3.0版本)库(百度分享资源:http://pan.baidu.com/s/1jGxHE3k),截止本文发布,官方最新版本是4.0.5.0,官方地址:http://stsdb.com/

 

using System;
using System.Collections.Generic;

namespace STSDB
{
    [Serializable]
    public class TStudent
    {
        public TStudent()
        {
        }
        public string Name { get; set; }
        public int Age { get; set; }
        public int GroupNumber { get; set; }
        public List<TCourse> CourseList { get; set; }
    }
}
using System;

namespace STSDB
{
    [Serializable]
    public class TCourse
    {
        public string CourseName { get; set; }
        public string Teacher { get; set; }
        public int Score { get; set; }
    }
}
演示代码:
/*
 * 1. STSdb 4.0 是一个开源的NoSQL 数据库和虚拟文件系统,支持实时索引,完全用c#开发的。
 * 引擎原理基于WaterfallTree(瀑布树)数据结构搭建
 * 
 * 
 * 2.特性
 * 支持几十亿级别的数据存取
 * 支持TB级别文件大小
 * 实时索引
 * 内置压缩
 * 内置序列化
 * 支持稀疏分散的文件(byte[])
 * 存储内存可控
 * 支持多线程,且线程安全
 *  Storage  engine  instance  is  thread-safe.  Creating  (opening)  XTable  and  XFile  instances  in  one  storage  engine  from 
    different threads is thread-safe.
    XTable and XFile instances are also thread-safe. Manipulating different XTable/XFile instances from different threads 
    is thread-safe.
 * 
 * 3.缺点
 * 不支持事务
 * 同时处理所有打开的表
 * 
 * 支持多种情况下的数据引擎连接
   IStorageEngine engine = STSdb.FromMemory();              //从内存中读取
   IStorageEngine engine = STSdb.FromStream(stream);        //从数据流中读取
   IStorageEngine engine = STSdb.FromHeap(heap);            //从堆栈中读取
   IStorageEngine engine = STSdb.FromNetwork(host, port);   //从远程地址读取
  
 * 
 * 
 */

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace STSDB
{
    using Newtonsoft.Json;
    using STSdb4.Data;
    using STSdb4.Database;
    using STSdb4.Storage;
    using STSdb4.WaterfallTree;
    using STSdb4.Remote.Heap;

    class Program
    {
        static void Main(string[] args)
        {
            ExecuteCode(WriteData);
            ExecuteCode(ReadData);
            //ExecuteCode(DatabaseSchemeInfo);

            //ExecuteCode(ReadItem);
            //ExecuteCode(DeleteItems);
            //ExecuteCode(ReadItem);

            //ExecuteCode(GetRecord);
            //ExecuteCode(PageRecord);

            //ExecuteCode(Others);
            //ExecuteCode(ReNameTable);

            //ExecuteCode(ExistsTable);
            //ExecuteCode(DeleteTable);
            //ExecuteCode(ExistsTable);

            #region test
            //bool quit = false;
            //while (!quit)
            //{
            //    Console.Write("get item data: ");
            //    string demo = Console.ReadLine();
            //    switch (demo)
            //    {
            //        case "Y":
            //            break;
            //        case "Q":
            //            quit = true;
            //            break;
            //        default:
            //            Console.WriteLine("Choose a Word between Y and Q(to quit)");
            //            break;
            //    }
            //}
            #endregion

            Console.ReadKey();
        }
        /// <summary>执行方法</summary>
        static void ExecuteCode(Action act)
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            act();

            stopwatch.Stop();
            TimeSpan timespan = stopwatch.Elapsed;

            Console.WriteLine("运行{0}秒", timespan.TotalSeconds);
        }

        /// <summary>
        /// 数据库名
        /// </summary>
        /// <remarks>文件名和扩展名不限制</remarks>
        protected static string DataBase = "ClassDB.db";
        /// <summary>
        /// 学生表名
        /// </summary>
        protected static string TableName = "tb_student";
        /// <summary>
        /// 【新】学生表名
        /// </summary>
        protected static string NewTableName = "new_tb_student";
        /// <summary>
        /// XFile
        /// </summary>
        protected static string XFileName = "tb_file";

        #region 基本操作
        /// <summary>
        /// 创建库,写入数据
        /// </summary>
        static void WriteData()
        {
            /*
             * ①:没有数据库会自动创建的,默认目录和应用程序目录一致;
             * ②:打开表,Key支持组合结构 => OpenXTable<TKey, TRecord>
             */
            using (IStorageEngine engine = STSdb.FromFile(DataBase)) //①
            {
                var table = engine.OpenXTable<int, TStudent>(TableName); //②
                //var table2 = engine.OpenXTable<TKey, TTick>("table2"); //支持key嵌套
                for (int i = 0; i < 1000; i++)
                {
                    table[i] = new TStudent
                    {
                        Name = "Jon_" + i.ToString(),
                        Age = new Random().Next(25, 30),
                        GroupNumber = i + (new Random().Next(310, 399)),
                        CourseList = new List<TCourse>()
                        {
                            new TCourse{
                                CourseName="C#高级编程"+i.ToString(),
                                Teacher="老陈"+i.ToString(), 
                                Score=80
                            },
                            new TCourse{
                                CourseName="C#函数式程序设计"+i.ToString(),
                                Teacher="老李"+i.ToString(),
                                Score=90
                            },
                            new TCourse{
                                CourseName="多线程实战应用"+i.ToString(),
                                Teacher="老张"+i.ToString(),
                                Score=95
                            },
                        }
                    };
                }
                engine.Commit();
            }
        }
        /// <summary>
        /// 读取数据
        /// </summary>
        static void ReadData()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                var table = engine.OpenXTable<int, TStudent>(TableName); //ITable:IEnumerable对象
                foreach (var item in table)
                    Console.WriteLine(JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented));

                Console.WriteLine(table.Count());   //TableName表中有100行数据
            }
        }

        /// <summary>
        /// 
        /// </summary>
        static void DatabaseSchemeInfo()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase)) //①
            {
                IDescriptor descriptor = engine[TableName];
                Console.WriteLine(descriptor.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                Console.WriteLine(descriptor.ModifiedTime.ToString("yyyy-MM-dd HH:mm:ss"));
                Console.WriteLine(descriptor.Name);
                //ID是表的唯一标识id,表一旦创建,它就创建了,后面只要表在就不会修改
                //重建表它会从新分配
                Console.WriteLine(descriptor.ID);

                //...
            }
        }

        /// <summary>
        /// 读取单条数据
        /// </summary>
        static void ReadItem()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                var table = engine.OpenXTable<int, TStudent>(TableName); //ITable: IEnumerable对象
                //var item = table.FirstOrDefault(x => x.Key <= 15 && x.Key >= 10);        //key是5的记录
                //table[10];
                var item = table.FirstOrDefault(x => x.Key == 5);        //key是5的记录
                if (item.Value != null)
                    Console.WriteLine(JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented));
                else
                    Console.WriteLine("key = 5 的记录不存在!");
                //Console.WriteLine("10<= key <= 15 的记录不存在!");
            }
        }

        static void AddItems()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                var table = engine.OpenXTable<int, TStudent>(TableName);
                //table[100] = new TStudent(){....};
                table.InsertOrIgnore(2, new TStudent());

                engine.Commit();
            }
        }

        /// <summary>
        /// 删除表数据
        /// </summary>
        static void DeleteItems()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                var table = engine.OpenXTable<int, TStudent>(TableName); //ITable:IEnumerable对象
                if (table != null)
                {
                    //table.Clear();          //清空表数据
                    table.Delete(5);        //删掉key是5的记录
                    //table.Delete(10, 15);  //删掉key从10到15的记录
                    engine.Commit();        //提交操作,不能少
                }
            }
        }

        /// <summary>
        /// 按需获取数据
        /// </summary>
        static void GetRecord()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                /*
                   Forward向前读取, Backward向后读取, 它们都有2个重载,下面重点说明第二个重载
                 * Forward(TKey from, bool hasFrom, TKey to, bool hasTo);
                 * Backward(TKey to, bool hasTo, TKey from, bool hasFrom);
                 * 超出范围的都不会排除,另外,查询范围超出也不会有影响,但是要注意一点,formkey和endkey的大小关系
                 * 
                 * 0<----------[(S)]----------------[(E)]------------->N
                 * 
                 */
                var table = engine.OpenXTable<int, TStudent>(TableName);
                var fiterTB = table.Forward(2, true, 9, true);    //索引从2到9
                //var fiterTB = table.Forward(2, false, 9, true);   //索引从0到9
                //var fiterTB = table.Forward(2, false, 9, false);  //索引从0到表结尾
                //var fiterTB = table.Forward(2, true, 9, false);   //索引从2到表结尾
                //Backward刚好相反
                foreach (var item in fiterTB)
                    Console.WriteLine(JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented));
            }
        }
        /// <summary>
        /// 数据分页
        /// </summary>
        static void PageRecord()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                int pageIndex = 2;
                int pageSize = 10;

                var table = engine.OpenXTable<int, TStudent>(TableName);
                var fiterTB = table.Skip(pageSize * (pageIndex - 1)).Take(pageSize);
                foreach (var item in fiterTB)
                    Console.WriteLine(JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented));
            }
        }
        /// <summary>
        /// 文件数和记录数
        /// </summary>
        static void Others()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                //表和虚拟文件的数量
                Console.WriteLine("数据库 " + DataBase + " 中有 {0} 张表:{1}", engine.Count, TableName);

                //表记录数
                var table = engine.OpenXTable<int, TStudent>(TableName);
                Console.WriteLine("表" + TableName + "中有" + table.Count() + "条记录");
            }
        }

        /// <summary>
        /// 表是否存在
        /// </summary>
        static void ExistsTable()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                //判断表存在与否
                //bool exists = engine.Exists(NewTableName);
                //Console.WriteLine(NewTableName + " exist?=>{0}", exists.ToString());

                bool exists = engine.Exists(TableName);
                Console.WriteLine(TableName + " exist?=>{0}", exists.ToString());
            }
        }

        /// <summary>
        /// 重命名表名
        /// </summary>
        static void ReNameTable()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                //判断表存在与否
                bool exists = engine.Exists(TableName);
                Console.WriteLine(TableName + " exist? =>{0}", exists.ToString());

                //表重命名
                engine.Rename(TableName, NewTableName);
                Console.WriteLine("表" + TableName + "被重命名为:" + NewTableName);

                if (engine.Exists(TableName))
                    Console.WriteLine("old table name \"" + TableName + "\" exist");
                if (engine.Exists(NewTableName))
                    Console.WriteLine("new table name \"" + NewTableName + "\" exist");
            }
        }
        /// <summary>
        /// 删除表
        /// </summary>
        static void DeleteTable()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                //删除表
                engine.Delete(TableName);
                //engine.Delete(NewTableName);
                engine.Commit();
            }
        }
        #endregion

        #region XFile

        static void TestXFile()
        {
            using (IStorageEngine engine = STSdb.FromFile(DataBase))
            {
                XFile file = engine.OpenXFile(XFileName);

                Random random = new Random();
                byte[] buffer = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                for (int i = 0; i < 100; i++)
                {
                    long position = random.Next();

                    file.Seek(position, SeekOrigin.Begin);
                    file.Write(buffer, 0, buffer.Length);
                }
                engine.Commit();
            }
        }
        //XFile uses special XTable<long, byte[]> implementation to provide effective sparse file functionality.
        //One storage engine can have many files
        #endregion

        #region Client/Server

        static void ClientUpdateData()
        {
            using (IStorageEngine engine = STSdb.FromNetwork("localhost", 7182))
            {
                ITable<int, string> table = engine.OpenXTable<int, string>("table");
                for (int i = 0; i < 100000; i++)
                {
                    table[i] = i.ToString();
                }
                engine.Commit();
            }
        }

        static void ServerHandleData()
        {
            string _dbname = "test.stsdb4";
            using (IStorageEngine engine = STSdb.FromFile(_dbname))
            {
                var server = STSdb.CreateServer(engine, 7182);
                server.Start();
                //server is ready for connections
                //server.Stop();
            }
        }
        //The created server instance will listen on the specified port 
        //and receive/send data from/to the clients

        #endregion

        #region Memory Usage
        /*
         min/max children (branches) in each internal (non-leaf) node
         max operations in the root node
         min/max operations in each internal node
         min/max records in each leaf node
         number of cached nodes in the memory
         */
        static void MemoryUsageHandle()
        {
            using (StorageEngine engine = (StorageEngine)STSdb.FromFile(DataBase))
            {
                //下面的demo都是STS.DB的默认值设置

                //min/max children (branches) in each internal node
                engine.INTERNAL_NODE_MIN_BRANCHES = 2;
                engine.INTERNAL_NODE_MAX_BRANCHES = 4;
                //max operations in the root node
                engine.INTERNAL_NODE_MAX_OPERATIONS_IN_ROOT = 8 * 1024;
                //min/max operations in each internal node
                engine.INTERNAL_NODE_MIN_OPERATIONS = 64 * 1024;
                engine.INTERNAL_NODE_MAX_OPERATIONS = 128 * 1024;
                //min/max records in each leaf node
                engine.LEAF_NODE_MIN_RECORDS = 16 * 1024;
                engine.LEAF_NODE_MAX_RECORDS = 128 * 1024; //at least 2 x MIN_RECORDS
                //number of cached nodes in memory
                engine.CacheSize = 32;
            }
        }

        #endregion

        #region Heap

        /*using =>
            STSdb4.WaterfallTree;
            STSdb4.Storage;
            STSdb4.Remote.Heap;
        */
        static void HeaperEngine()
        {
            //Server端
            IHeap heap = new Heap(new FileStream("Heap.db", FileMode.OpenOrCreate));
            HeapServer server = new HeapServer(heap, 7183); //监听堆服务器
            server.Start(); //开始监听

            //从远程堆中创建 IStorageEngine 引擎,并处理数据
            //using (IStorageEngine engine = STSdb.FromHeap(new RemoteHeap("host", 7183)))
            //{
            //    ITable<int, string> table = engine.OpenXTable<int, string>("table");
            //    for (int i = 0; i < 100000; i++)
            //    {
            //        table[i] = i.ToString();
            //    }
            //    engine.Commit();
            //}
        }
        #endregion

        //...

    }
}


 

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您可以使用哪些工具來監視MySQL性能?您可以使用哪些工具來監視MySQL性能?Apr 23, 2025 am 12:21 AM

如何有效監控MySQL性能?使用mysqladmin、SHOWGLOBALSTATUS、PerconaMonitoringandManagement(PMM)和MySQLEnterpriseMonitor等工具。 1.使用mysqladmin查看連接數。 2.用SHOWGLOBALSTATUS查看查詢數。 3.PMM提供詳細性能數據和圖形化界面。 4.MySQLEnterpriseMonitor提供豐富的監控功能和報警機制。

MySQL與SQL Server有何不同?MySQL與SQL Server有何不同?Apr 23, 2025 am 12:20 AM

MySQL和SQLServer的区别在于:1)MySQL是开源的,适用于Web和嵌入式系统,2)SQLServer是微软的商业产品,适用于企业级应用。两者在存储引擎、性能优化和应用场景上有显著差异,选择时需考虑项目规模和未来扩展性。

在哪些情況下,您可以選擇SQL Server而不是MySQL?在哪些情況下,您可以選擇SQL Server而不是MySQL?Apr 23, 2025 am 12:20 AM

在需要高可用性、高級安全性和良好集成性的企業級應用場景下,應選擇SQLServer而不是MySQL。 1)SQLServer提供企業級功能,如高可用性和高級安全性。 2)它與微軟生態系統如VisualStudio和PowerBI緊密集成。 3)SQLServer在性能優化方面表現出色,支持內存優化表和列存儲索引。

MySQL如何處理角色集和碰撞?MySQL如何處理角色集和碰撞?Apr 23, 2025 am 12:19 AM

mySqlManagesCharacterSetsetSandCollat​​ionsyutusututf-8asthEdeFault,允許ConfigurationAtdataBase,table和columnlevels,AndrequiringCarefullageLignmentToavoidMismatches.1)setDefeaultCharactersetTercharactersetEtCollacterSeteTandColletationForAdataBase.2)conformentcollecharactersettersetertersetcollat​​ertersetcollat​​ioncollat​​ion

MySQL中有什麼觸發器?MySQL中有什麼觸發器?Apr 23, 2025 am 12:11 AM

MySQL觸發器是與表相關聯的自動執行的存儲過程,用於在特定數據操作時執行一系列操作。 1)觸發器定義與作用:用於數據校驗、日誌記錄等。 2)工作原理:分為BEFORE和AFTER,支持行級觸發。 3)使用示例:可用於記錄薪資變更或更新庫存。 4)調試技巧:使用SHOWTRIGGERS和SHOWCREATETRIGGER命令。 5)性能優化:避免複雜操作,使用索引,管理事務。

您如何在MySQL中創建和管理用戶帳戶?您如何在MySQL中創建和管理用戶帳戶?Apr 22, 2025 pm 06:05 PM

在MySQL中創建和管理用戶賬戶的步驟如下:1.創建用戶:使用CREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';2.分配權限:使用GRANTSELECT,INSERT,UPDATEONmydatabase.TO'newuser'@'localhost';3.修正權限錯誤:使用REVOKEALLPRIVILEGESONmydatabase.FROM'newuser'@'localhost';然後重新分配權限;4.優化權限:使用SHOWGRA

MySQL與Oracle有何不同?MySQL與Oracle有何不同?Apr 22, 2025 pm 05:57 PM

MySQL適合快速開發和中小型應用,Oracle適合大型企業和高可用性需求。 1)MySQL開源、易用,適用於Web應用和中小型企業。 2)Oracle功能強大,適合大型企業和政府機構。 3)MySQL支持多種存儲引擎,Oracle提供豐富的企業級功能。

與其他關係數據庫相比,使用MySQL的缺點是什麼?與其他關係數據庫相比,使用MySQL的缺點是什麼?Apr 22, 2025 pm 05:49 PM

MySQL相比其他關係型數據庫的劣勢包括:1.性能問題:在處理大規模數據時可能遇到瓶頸,PostgreSQL在復雜查詢和大數據處理上表現更優。 2.擴展性:水平擴展能力不如GoogleSpanner和AmazonAurora。 3.功能限制:在高級功能上不如PostgreSQL和Oracle,某些功能需要更多自定義代碼和維護。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!