• 阿里云AliYun表格存储(Table Store)相关案例


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Aliyun.OTS;
    using Aliyun.OTS.DataModel;
    using Aliyun.OTS.Request;
    using Aliyun.OTS.Response;
    using Aliyun.OTS.DataModel.ConditionalUpdate;
    using Aliyun.OTS.Samples;
    
    namespace Sample1
    {
        class Program
        {
            private static string TableName = "SampleTable";
            static void Main(string[] args)
            {
    
                #region 打开连接
                // 使用OTSClientConfig创建一个OtsClient对象
                var otsClient = Config.GetClient();
                #endregion
    
                #region 创建表
                ////创建主键列的schema,包括PK的个数,名称和类型
                ////第一个PK列为整数,名称是pk0,这个同时也是分片列
                ////第二个PK列为字符串,名称是pk1
                //var primaryKeySchema = new PrimaryKeySchema();
                //primaryKeySchema.Add("pk0", ColumnValueType.Integer);
                //primaryKeySchema.Add("pk1", ColumnValueType.String);
                ////通过表名和主键列的schema创建一个tableMeta
                //var tableMeta = new TableMeta("SampleTable", primaryKeySchema);
                //// 设定预留读吞吐量为0,预留写吞吐量为0
                //var reservedThroughput = new CapacityUnit(0, 0);
                //try
                //{
                //    // 构造CreateTableRequest对象
                //    var request = new CreateTableRequest(tableMeta, reservedThroughput);
                //    // 调用client的CreateTable接口,如果没有抛出异常,则说明成功,否则失败
                //    otsClient.CreateTable(request);
                //    Console.WriteLine("Create table succeeded.");
                //}
                //// 处理异常
                //catch (Exception ex)
                //{
                //    Console.WriteLine("Create table failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 列出所有表
                //var request = new ListTableRequest();
                //try
                //{
                //    var response = otsClient.ListTable(request);
                //    foreach (var tableName in response.TableNames)
                //    {
                //        Console.WriteLine("Table name:{0}", tableName);
                //    }
                //    Console.WriteLine("List table succeeded.");
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine("List table failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 获取表的描述信息
                //try
                //{
                //    var request = new DescribeTableRequest("SampleTable");
                //    var response = otsClient.DescribeTable(request);
                //    // 打印表的描述信息
                //    Console.WriteLine("Describe table succeeded.");
                //    Console.WriteLine("LastIncreaseTime: {0}", response.ReservedThroughputDetails.LastIncreaseTime);
                //    Console.WriteLine("LastDecreaseTime: {0}", response.ReservedThroughputDetails.LastDecreaseTime);
                //    Console.WriteLine("NumberOfDecreaseToday: {0}", response.ReservedThroughputDetails.LastIncreaseTime);
                //    Console.WriteLine("ReadCapacity: {0}", response.ReservedThroughputDetails.CapacityUnit.Read);
                //    Console.WriteLine("WriteCapacity: {0}", response.ReservedThroughputDetails.CapacityUnit.Write);
                //}
                //catch (Exception ex)
                //{
                //    //如果抛出异常,则说明执行失败,打印错误信息
                //    Console.WriteLine("Describe table failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 删除表
                //var request = new DeleteTableRequest("SampleTable");
                //try
                //{
                //    otsClient.DeleteTable(request);
                //    Console.Writeline("Delete table succeeded.");
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine("Delete table failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                /*表格存储的 SDK 提供了 PutRow、GetRow、UpdateRow 和 DeleteRow 等单行操作的接口。*/
    
                #region 插入数据
                ///*
                //    RowExistenceExpectation.IGNORE 表示不管此行是否已经存在,都会插入新数据,如果之前有会被覆盖。
                //    RowExistenceExpectation.EXPECT_EXIST 表示只有此行存在时,才会插入新数据,此时,原有数据也会被覆盖。
                //    RowExistenceExpectation.EXPECT_NOT_EXIST 表示只有此行不存在时,才会插入数据,否则不执行。             
                // */
                //// 定义行的主键,必须与创建表时的TableMeta中定义的一致
                //var primaryKey = new PrimaryKey();
                //primaryKey.Add("pk0", new ColumnValue(0));
                //primaryKey.Add("pk1", new ColumnValue("abc"));
                //// 定义要写入改行的属性列
                //var attribute = new AttributeColumns();
                //attribute.Add("col0", new ColumnValue(0));
                //attribute.Add("col1", new ColumnValue("a"));
                //attribute.Add("col2", new ColumnValue(true));
                //try
                //{
                //    // 构造插入数据的请求对象,RowExistenceExpectation.IGNORE表示不管此行是否存在都执行
                //    var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
                //                            primaryKey, attribute);
                //    // 调用PutRow接口插入数据
                //    otsClient.PutRow(request);
                //    // 如果没有抛出异常,则说明执行成功
                //    Console.WriteLine("Put row succeeded.");
                //}
                //catch (Exception ex)
                //{
                //    // 如果抛出异常,则说明执行失败,打印出错误信息
                //    Console.WriteLine("Put row failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 设置条件插入数据
                /*
                    条件不仅支持单个条件,也支持多个条件组合。例如,col1 大于 5 且 pk2 小于’xyz’时插入数据。
                    属性列和主键列都支持条件。
                    当条件中的列在某行不存在时,可以通过 RelationCondition 中的 PassIfMissing 控制,默认是 true。             
                 */
                //// 定义行的主键,必须与创建表时的TableMeta中定义的一致
                //var primaryKey = new PrimaryKey();
                //primaryKey.Add("pk0", new ColumnValue(0));
                //primaryKey.Add("pk1", new ColumnValue("abc"));
                //// 定义要写入改行的属性列
                //AttributeColumns attribute = new AttributeColumns();
                //attribute.Add("col0", new ColumnValue(0));
                //attribute.Add("col1", new ColumnValue("a"));
                //attribute.Add("col2", new ColumnValue(true));
                //var request = new PutRowRequest("SampleTable", new Condition(RowExistenceExpectation.EXPECT_EXIST),
                //                            primaryKey, attribute);
                //// 当col0列的值大于24的时候,允许再次put row,覆盖掉原值
                //try
                //{
                //    request.Condition.ColumnCondition = new RelationalCondition("col0",
                //                                        RelationalCondition.CompareOperator.GREATER_THAN,
                //                                        new ColumnValue(24));
                //    otsClient.PutRow(request);
                //    Console.WriteLine("Put row succeeded.");
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine("Put row failed. error:{0}", ex.Message);
                //}
                #endregion
    
                #region 读取一行数据
                //// 定义行的主键,必须与创建表时的TableMeta中定义的一致
                //PrimaryKey primaryKey = new PrimaryKey();
                //primaryKey.Add("pk0", new ColumnValue(0));
                //primaryKey.Add("pk1", new ColumnValue("abc"));
                //try
                //{
                //    // 构造查询请求对象,这里未指定读哪列,默认读整行
                //    var request = new GetRowRequest("SampleTable", primaryKey);
                //    // 调用GetRow接口查询数据
                //    var response = otsClient.GetRow(request);
                //    // 输出此行的数据,这里省略,详见下面GitHub的链接
                //    // 如果没有抛出异常,则说明成功
                //    PrimaryKey primaryKeyRead = response.PrimaryKey;
                //    AttributeColumns attributesRead = response.Attribute;
    
                //    Console.WriteLine("Primary key read: ");
                //    foreach (KeyValuePair<string, ColumnValue> entry in primaryKeyRead)
                //    {
                //        Console.WriteLine(entry.Key + ":" + PrintColumnValue(entry.Value));
                //    }
    
                //    Console.WriteLine("Attributes read: ");
                //    foreach (KeyValuePair<string, ColumnValue> entry in attributesRead)
                //    {
                //        Console.WriteLine(entry.Key + ":" + PrintColumnValue(entry.Value));
                //    }
    
                //    Console.WriteLine("Get row succeed.");
                //}
                //catch (Exception ex)
                //{
                //    // 如果抛出异常,说明执行失败,打印出错误信息
                //    Console.WriteLine("Update table failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 更新一行数据
                //// 定义行的主键,必须与创建表时的TableMeta中定义的一致
                //PrimaryKey primaryKey = new PrimaryKey();
                //primaryKey.Add("pk0", new ColumnValue(0));
                //primaryKey.Add("pk1", new ColumnValue("abc"));
                //// 定义要写入改行的属性列
                //UpdateOfAttribute attribute = new UpdateOfAttribute();
                //attribute.AddAttributeColumnToPut("col0", new ColumnValue(0));
                //attribute.AddAttributeColumnToPut("col1", new ColumnValue("b")); // 将原先的值'a'改为'b'
                //attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
                //try
                //{
                //    // 构造更新行的请求对象,RowExistenceExpectation.IGNORE表示不管此行是否存在都执行
                //    var request = new UpdateRowRequest("SampleTable", new Condition(RowExistenceExpectation.IGNORE),
                //                            primaryKey, attribute);
                //    // 调用UpdateRow接口执行
                //    otsClient.UpdateRow(request);
                //    // 如果没有抛出异常,则说明执行成功
                //    Console.WriteLine("Update row succeeded.");
                //}
                //catch (Exception ex)
                //{
                //    // 如果抛出异常,说明执行失败,打印异常信息
                //    Console.WriteLine("Update row failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 删除一行数据
                // 要删除的行的PK列分别为0和"abc"
                //var primaryKey = new PrimaryKey();
                //primaryKey.Add("pk0", new ColumnValue(0));
                //primaryKey.Add("pk1", new ColumnValue("abc"));
                //try
                //{
                //    // 构造请求,Condition.EXPECT_EXIST表示只有此行存在时才执行
                //    var condition = new Condition(RowExistenceExpectation.EXPECT_EXIST);
                //    var deleteRowRequest = new DeleteRowRequest("SampleTable", condition, primaryKey);
                //    // 调用DeleteRow接口执行删除
                //    otsClient.DeleteRow(deleteRowRequest);
                //    // 如果没有抛出异常,则表示成功
                //    Console.WriteLine("Delete table succeeded.");
                //}
                //catch (Exception ex)
                //{
                //    // 如果抛出异常,说明删除失败,打印粗错误信息
                //    Console.WriteLine("Delete table failed, exception:{0}", ex.Message);
                //}
                #endregion
    
                #region 批量删除数据
                //BatchWriteRow();
                #endregion
    
                #region 根据条件获取多条数据
                //GetRange();
                #endregion
    
                Console.ReadKey();
            }
    
    
    
    
            private static void PrepareTable()
            {
                // 创建表
                OTSClient otsClient = Config.GetClient();
    
                IList<string> tables = otsClient.ListTable(new ListTableRequest()).TableNames;
                if (tables.Contains(TableName))
                {
                    return;
                }
    
    
                PrimaryKeySchema primaryKeySchema = new PrimaryKeySchema();
                primaryKeySchema.Add("pk0", ColumnValueType.Integer);
                primaryKeySchema.Add("pk1", ColumnValueType.String);
                TableMeta tableMeta = new TableMeta(TableName, primaryKeySchema);
    
                CapacityUnit reservedThroughput = new CapacityUnit(1, 1);
                CreateTableRequest request = new CreateTableRequest(tableMeta, reservedThroughput);
                otsClient.CreateTable(request);
    
            }
    
            private static void PrepareData()
            {
                OTSClient otsClient = Config.GetClient();
    
                // 插入100条数据
                for (int i = 0; i < 100; i++)
                {
                    PrimaryKey primaryKey = new PrimaryKey();
                    primaryKey.Add("pk0", new ColumnValue(i));
                    primaryKey.Add("pk1", new ColumnValue("abc"));
    
                    // 定义要写入改行的属性列
                    AttributeColumns attribute = new AttributeColumns();
                    attribute.Add("col0", new ColumnValue(0));
                    attribute.Add("col1", new ColumnValue("a"));
                    attribute.Add("col2", new ColumnValue(i % 3 != 0));
                    PutRowRequest request = new PutRowRequest(TableName, new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
    
                    otsClient.PutRow(request);
                }
            }
    
            private static void BatchWriteRow()
            {
                Console.WriteLine("Start batch write row...");
                PrepareTable();
                PrepareData();
                OTSClient otsClient = Config.GetClient();
    
                // 一次批量导入100行数据
                var request = new BatchWriteRowRequest();
                var rowChanges = new RowChanges();
                for (int i = 0; i < 100; i++)
                {
                    PrimaryKey primaryKey = new PrimaryKey();
                    primaryKey.Add("pk0", new ColumnValue(i));
                    primaryKey.Add("pk1", new ColumnValue("abc"));
    
                    // 定义要写入改行的属性列
                    UpdateOfAttribute attribute = new UpdateOfAttribute();
                    attribute.AddAttributeColumnToPut("col0", new ColumnValue(0));
                    attribute.AddAttributeColumnToPut("col1", new ColumnValue("a"));
                    attribute.AddAttributeColumnToPut("col2", new ColumnValue(true));
    
                    rowChanges.AddUpdate(new Condition(RowExistenceExpectation.IGNORE), primaryKey, attribute);
                }
    
                request.Add(TableName, rowChanges);
    
                var response = otsClient.BatchWriteRow(request);
                var tableRows = response.TableRespones;
                var rows = tableRows[TableName];
    
                int succeedRows = 0;
                int failedRows = 0;
                foreach (var row in rows.UpdateResponses)
                {
                    // 注意:batch操作可能部分成功部分失败,需要为每行检查状态
                    if (row.IsOK)
                    {
                        succeedRows++;
                    }
                    else
                    {
                        Console.WriteLine("Read row failed: " + row.ErrorMessage);
                        failedRows++;
                    }
                }
    
                Console.WriteLine("SucceedRows: " + succeedRows);
                Console.WriteLine("FailedRows: " + failedRows);
            }
    
            public static void GetRange()
            {
                Console.WriteLine("Start get range...");
    
                PrepareTable();
                PrepareData();
    
                OTSClient otsClient = Config.GetClient();
                // 读取 (0, INF_MIN)到(100, INF_MAX)这个范围内的所有行
                PrimaryKey inclusiveStartPrimaryKey = new PrimaryKey();
                inclusiveStartPrimaryKey.Add("pk0", new ColumnValue(0));
                inclusiveStartPrimaryKey.Add("pk1", ColumnValue.INF_MIN);
    
                PrimaryKey exclusiveEndPrimaryKey = new PrimaryKey();
                exclusiveEndPrimaryKey.Add("pk0", new ColumnValue(100));
                exclusiveEndPrimaryKey.Add("pk1", ColumnValue.INF_MAX);
                GetRangeRequest request = new GetRangeRequest(TableName, GetRangeDirection.Forward, inclusiveStartPrimaryKey, exclusiveEndPrimaryKey);
    
                GetRangeResponse response = otsClient.GetRange(request);
                IList<RowDataFromGetRange> rows = response.RowDataList;
                PrimaryKey nextStartPrimaryKey = response.NextPrimaryKey;
                while (nextStartPrimaryKey != null)
                {
                    request = new GetRangeRequest(TableName, GetRangeDirection.Forward, nextStartPrimaryKey, exclusiveEndPrimaryKey);
                    response = otsClient.GetRange(request);
                    nextStartPrimaryKey = response.NextPrimaryKey;
                    foreach (RowDataFromGetRange row in response.RowDataList)
                    {
                        rows.Add(row);
                    }
                }
    
                foreach (RowDataFromGetRange row in rows)
                {
                    Console.WriteLine("-----------------");
                    foreach (KeyValuePair<string, ColumnValue> entry in row.PrimaryKey)
                    {
                        Console.WriteLine(entry.Key + ":" + PrintColumnValue(entry.Value));
                    }
                    foreach (KeyValuePair<string, ColumnValue> entry in row.Attribute)
                    {
                        Console.WriteLine(entry.Key + ":" + PrintColumnValue(entry.Value));
                    }
                    Console.WriteLine("-----------------");
                }
    
                Console.WriteLine("TotalRowsRead: " + rows.Count);
            }
    
            private static string PrintColumnValue(ColumnValue value)
            {
                switch (value.Type)
                {
                    case ColumnValueType.String: return value.StringValue;
                    case ColumnValueType.Integer: return value.IntegerValue.ToString();
                    case ColumnValueType.Boolean: return value.BooleanValue.ToString();
                    case ColumnValueType.Double: return value.DoubleValue.ToString();
                    case ColumnValueType.Binary: return value.BinaryValue.ToString();
                }
                throw new Exception("Unknow type.");
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Aliyun.OTS;
    
    namespace Aliyun.OTS.Samples
    {
        internal class Config
        {
            public static string AccessKeyId = "";
            public static string AccessKeySecret = "";
            public static string Endpoint = "";
            public static string InstanceName = "";
            private static OTSClient OtsClient = null;
    
            public static OTSClient GetClient()
            {
                if (OtsClient != null)
                {
                    return OtsClient;
                }
    
                OTSClientConfig config = new OTSClientConfig(Endpoint, AccessKeyId, AccessKeySecret, InstanceName);
                config.OTSDebugLogHandler = null;
                config.OTSErrorLogHandler = null;
                OtsClient = new OTSClient(config);
                return OtsClient;
            }
        }
    }


  • 相关阅读:
    笔试算法题(51):简介
    笔试算法题(50):简介
    笔试算法题(49):简介
    笔试算法题(48):简介
    笔试算法题(47):简介
    笔试算法题(46):简介
    SQL Server 笔记
    SQL Server 2008 安装重启电脑失败
    列举某个目录文件
    Linux LAMP 配置
  • 原文地址:https://www.cnblogs.com/smartsmile/p/6234044.html
Copyright © 2020-2023  润新知