数据库
首页 > 数据库> > C# SqlBuilder類代碼示例

C# SqlBuilder類代碼示例

作者:互联网

本文整理匯總了C#中SqlBuilder類的典型用法代碼示例。如果您正苦於以下問題:C# SqlBuilder類的具體用法?C# SqlBuilder怎麽用?C# SqlBuilder使用的例子?那麽恭喜您, 這裏精選的類代碼示例或許可以為您提供幫助。



SqlBuilder類屬於命名空間,在下文中一共展示了SqlBuilder類的20個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的C#代碼示例。

示例1: List

 
        /// <summary>
        /// The list of results.
        /// </summary>
        /// <param name="maxResults">The max results.</param>
        /// <param name="start">The start</param>
        /// <param name="finish">The finish</param>
        /// <param name="orderBy">The order by.</param>
        /// <returns>The result set</returns>
        public override IEnumerable<Guid> List(
            int maxResults,
            DateTime? start = null,
            DateTime? finish = null,
            ListResultsOrder orderBy = ListResultsOrder.Descending)
        {
            var builder = new SqlBuilder();
            var t = builder.AddTemplate("select Id from MiniProfilers /**where**/ /**orderby**/ LIMIT(" + maxResults + ")");

            if (start != null)
            {
                builder.Where("Started > @start", new { start });
            }
            if (finish != null)
            {
                builder.Where("Started < @finish", new { finish });
            }

            builder.OrderBy(orderBy == ListResultsOrder.Descending ? "Started desc" : "Started asc");

            using (var conn = GetOpenConnection())
            {
                return conn.Query<Guid>(t.RawSql, t.Parameters).ToList();
            }
        }
開發者ID:haroonxml,項目名稱:dotnet,代碼行數:33,代碼來源:SqliteMiniProfilerStorage.cs

示例2: BuilderSelectClause

 
        public void BuilderSelectClause()
        {
            using (var dbConn = dbFactory.OpenDbConnection())
            using (var dbCmd = dbConn.CreateCommand())
            {
                var rand = new Random(8675309);
                var data = new List<User>();
                for (var i = 0; i < 100; i++)
                {
                    var nU = new User { Age = rand.Next(70), Id = i, Name = Guid.NewGuid().ToString() };
                    data.Add(nU);
                    dbCmd.Insert(nU);
                    nU.Id = (int) dbCmd.GetLastInsertId();
                }

                var builder = new SqlBuilder();
                var justId = builder.AddTemplate("SELECT /**select**/ FROM Users");
                var all = builder.AddTemplate("SELECT /**select**/, Name, Age FROM Users");

                builder.Select("Id");

                var ids = dbCmd.Query<int>(justId.RawSql, justId.Parameters);
                var users = dbCmd.Query<User>(all.RawSql, all.Parameters);

                foreach (var u in data)
                {
                    Assert.That(ids.Any(i => u.Id == i), "Missing ids in select");
                    Assert.That(users.Any(a => a.Id == u.Id && a.Name == u.Name && a.Age == u.Age), "Missing users in select");
                }
            }
        }
開發者ID:Toshik,項目名稱:ServiceStack.OrmLite,代碼行數:31,代碼來源:SqlMapperTests.cs

示例3: GetAlls

 
 public static IEnumerable<BusOperator> GetAlls()
 {
     var builder = new SqlBuilder();
     var template = builder.AddTemplate(@"
     select *
     from BusOperator bo
     order by bo.Name");
     return Current.DB.Query<BusOperator>(template.RawSql, template.Parameters);
 }
開發者ID:phithakul,項目名稱:JBus,代碼行數:9,代碼來源:BusOperator.cs

示例4: TestLessThanConstraint

 
        public void TestLessThanConstraint()
        {
            SqlBuilder builder = new SqlBuilder( StatementType.Count, typeof(MailingList) );
            builder.AddConstraint( Operator.LessThan, "Id", 3 );
            int count = GetCount( builder );
            Assert.AreEqual( 2, count );
        }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:7,代碼來源:TestConstraint.cs

示例5: TestGreaterThanOrEqualsConstraint

 
        public void TestGreaterThanOrEqualsConstraint()
        {
            SqlBuilder builder = new SqlBuilder( StatementType.Count, typeof(MailingList) );
            builder.AddConstraint( Operator.GreaterThanOrEquals, "Id", 3 );
            int count = GetCount( builder );
            Assert.AreEqual( 1, count );
        }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:7,代碼來源:TestConstraint.cs

示例6: GetCount

 
        private int GetCount( SqlBuilder builder )
        {
            SqlStatement statement = builder.GetStatement();
            SqlResult result = statement.Execute();
            int count = result.Count;
            return count;
        }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:7,代碼來源:TestConstraint.cs

示例7: TestCRUD

 
        public void TestCRUD()
        {
            // skip test if GUIDs are not supported by database backend
            if( runTest )
            {
                o1 = new GuidHolder( 42 );
                // insert
                o1.Persist();
                // select
                o2 = GuidHolder.Retrieve( o1.Id );
                // verify select/insert
                Assert.IsNotNull( o2.Id, "The object could not be retrieved from the database!" );
                Assert.AreEqual( o1.Id, o2.Id, "The object could not be retrieved from the database!" );
                Assert.AreEqual( o1.SomeValue, o2.SomeValue, "The object could not be retrieved from the database!" );
                // update
                o2.SomeValue = 1234;
                o2.Persist();
                // verify update
                o1 = GuidHolder.Retrieve( o2.Id );
                Assert.AreEqual( o2.Id, o1.Id, "The object could not be retrieved from the database!" );
                // delete
                o2.Remove();
                // verify delete by counting the number of rows
                SqlBuilder sb = new SqlBuilder( StatementType.Count, typeof(GuidHolder) );
                sb.AddConstraint( Operator.Equals, "Id", o1.Id );
                SqlResult sr = Broker.Execute( sb.GetStatement( true ) );
                Assert.AreEqual( 0, sr.Count, "Object not removed" );
            }
        }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:29,代碼來源:TestGuid.cs

示例8: InitChannels

 
    private void InitChannels()
    {
      listViewChannels.Clear();
      listViewChannels.BeginUpdate();
      try
      {
        SqlBuilder sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof (Channel));
        if (checkBoxGuideChannels.Checked)
        {
          sb.AddConstraint(Operator.Equals, "visibleInGuide", 1);
        }
        sb.AddConstraint(Operator.Equals, "isTv", 1);
        sb.AddOrderByField(true, "sortOrder");
        sb.AddOrderByField(true, "displayName");
        SqlStatement stmt = sb.GetStatement(true);
        IList<Channel> channels = ObjectFactory.GetCollection<Channel>(stmt.Execute());

        for (int i = 0; i < channels.Count; i++)
        {
          // TODO: add imagelist with channel logos from MP :)
          ListViewItem curItem = new ListViewItem(channels[i].DisplayName);
          curItem.Tag = channels[i];
          listViewChannels.Items.Add(curItem);
        }
      }
      finally
      {
        listViewChannels.EndUpdate();
      }
      mpButtonOk.Enabled = (listViewChannels.Items.Count > 0);
    }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:31,代碼來源:FormSelectListChannel.cs

示例9: Prepare

 
        internal override PreparedDatabaseCommand Prepare(DocumentStore store, Guid etag, int uniqueParameterIdentifier)
        {
            var values = ConvertAnonymousToProjections(table, projections);

            values[table.EtagColumn] = etag;
            values[table.ModifiedAtColumn] = DateTimeOffset.Now;

            var sql = new SqlBuilder()
                .Append("update {0} set {1} where {2}[email protected]{3}",
                        store.Database.FormatTableNameAndEscape(table.Name),
                        string.Join(", ", from column in values.Keys select column.Name + "[email protected]" + column.Name + uniqueParameterIdentifier),
                        table.IdColumn.Name,
                        uniqueParameterIdentifier)
                .Append(!lastWriteWins, "and {0}[email protected]{1}",
                        table.EtagColumn.Name,
                        uniqueParameterIdentifier)
                .ToString();

            var parameters = MapProjectionsToParameters(values, uniqueParameterIdentifier);
            AddTo(parameters, "@Id" + uniqueParameterIdentifier, key, SqlTypeMap.Convert(table.IdColumn).DbType, null);

            if (!lastWriteWins)
            {
                AddTo(parameters, "@CurrentEtag" + uniqueParameterIdentifier, currentEtag, SqlTypeMap.Convert(table.EtagColumn).DbType, null);
            }

            return new PreparedDatabaseCommand
            {
                Sql = sql,
                Parameters = parameters.Values.ToList(),
                ExpectedRowCount = 1
            };
        }
開發者ID:dcga,項目名稱:HybridDb,代碼行數:33,代碼來源:UpdateCommand.cs

示例10: Prepare

 
        internal override PreparedDatabaseCommand Prepare(DocumentStore store, Guid etag, int uniqueParameterIdentifier)
        {
            var sql = new SqlBuilder()
                .Append("delete from {0} where {1} = @Id{2}",
                        store.Database.FormatTableNameAndEscape(table.Name),
                        table.IdColumn.Name,
                        uniqueParameterIdentifier)
                .Append(!lastWriteWins,
                        "and {0} = @CurrentEtag{1}",
                        table.EtagColumn.Name,
                        uniqueParameterIdentifier)
                .ToString();

            var parameters = new Dictionary<string, Parameter>();
            AddTo(parameters, "@Id" + uniqueParameterIdentifier, key, SqlTypeMap.Convert(table.IdColumn).DbType, null);

            if (!lastWriteWins)
            {
                AddTo(parameters, "@CurrentEtag" + uniqueParameterIdentifier, currentEtag, SqlTypeMap.Convert(table.EtagColumn).DbType, null);
            }

            return new PreparedDatabaseCommand
            {
                Sql = sql,
                Parameters = parameters.Values.ToList(),
                ExpectedRowCount = 1
            };
        }
開發者ID:dcga,項目名稱:HybridDb,代碼行數:28,代碼來源:DeleteCommand.cs

示例11: SqlPaging

 
        public void SqlPaging()
        {
            var b = new SqlBuilder()
                .Select("*")
                .From("Orders o")
                .Where("o.ShipCountry = @country ", new {country = "USA"})
                .OrderBy("CustomerID DESC");

            var paging = new
            {
                Page = 1,
                PageSize = 25
            };

            var t = b.AddTemplate(
                Templates.Combine(Templates.SqlServer.PagedSelection, Templates.Count), 
                paging);

            using (var db = new SqlConnection(ConnectionStrings.Northwind))
            {
                Console.WriteLine(t.RawSql);
                var results = db.QueryResultsSql<dynamic, int>(t.RawSql, t.Parameters);
                results.Set1.Should().HaveCount(paging.PageSize, "because thats how many are in the page");
                results.Set2.Single().Should().Be(122, "because thats how many there are");

            }
        }
開發者ID:ronnieoverby,項目名稱:UniqueNamespace.SqlBuilder,代碼行數:27,代碼來源:InsightTests.cs

示例12: Index

 
        /// <summary>
        /// GET: /search
        /// GET: /search/index
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string input, int? page, int? pageSize)
        {
            ViewBag.Input = input;

            page = Math.Max(page ?? 1, 1); // Adjust.
            pageSize = Math.Max(Math.Min(pageSize ?? 10, 100), 10); // Adjust.

            int start = ((page.Value - 1) * pageSize.Value) + 1;
            int finish = page.Value * pageSize.Value;
            var builder = new SqlBuilder();
            SqlBuilder.Template pager = null, counter = null;

            pager = builder.AddTemplate("SELECT * FROM (SELECT /**select**/, ROW_NUMBER() OVER (/**orderby**/) AS RowNumber FROM Questions Q /**where**/) AS Results WHERE RowNumber BETWEEN @start AND @finish ORDER BY RowNumber",
                new { start = start, finish = finish });

            counter = builder.AddTemplate("SELECT COUNT(*) FROM Questions Q /**where**/");

            builder.Select("Q.*");
            builder.OrderBy("Q.Time DESC");
            builder.Where("Q.Title LIKE @searchInput OR Q.Answer LIKE @searchInput", new { searchInput = "%" + input + "%" });

            var results = Current.DB.QueryMultiple(pager.RawSql, pager.Parameters).Read<Question>();
            var totals = Current.DB.Query<int>(counter.RawSql, counter.Parameters).First();

            ViewData["Href"] = "/search?";

            return View(new PagedList<Question>(results, page.Value, pageSize.Value, false, totals));
        }
開發者ID:friedr1c3,項目名稱:simple-faq,代碼行數:33,代碼來源:SearchController.cs

示例13: Query

 
        public static IEnumerable<Dictionary<string, object>> Query(this SqliteConnection connection, SqlBuilder sql, SqliteTransaction transaction = null, object sqlParams = null)
        {
            if (sql == null)
                throw new ArgumentNullException("sql", "sql cannot be null.");

            return Query(connection, sql.GetSql(), transaction, sqlParams);
        }
開發者ID:pcrockett,項目名稱:Ruminate,代碼行數:7,代碼來源:ConnectionExtensions.cs

示例14: TopClause

 
 /// <summary>
 /// Creates a TopClause with the given topCount and withTies.
 /// </summary>
 /// <param name="topCount"></param>
 /// <param name="withTies"></param>
 internal TopClause(int topCount, bool withTies)
 {
   SqlBuilder sqlBuilder = new SqlBuilder();
   sqlBuilder.Append(topCount.ToString(CultureInfo.InvariantCulture));
   this.topCount = sqlBuilder;
   this.withTies = withTies;
 }
開發者ID:yingfangdu,項目名稱:SQLiteNet,代碼行數:12,代碼來源:TopClause.cs

示例15: GetSetting

 
    /// <summary>
    /// gets a value from the database table "Setting"
    /// </summary>
    /// <returns>A Setting object with the stored value, if it doesnt exist the given default string will be the value</returns>
    private Setting GetSetting(string tagName, string defaultValue)
    {
      if (defaultValue == null)
      {
        return null;
      }
      if (tagName == null)
      {
        return null;
      }
      if (tagName == "")
      {
        return null;
      }
      SqlBuilder sb;
      try
      {
        sb = new SqlBuilder(Gentle.Framework.StatementType.Select, typeof(Setting));
      }
      catch (TypeInitializationException)
      {
        return new Setting(tagName,defaultValue);
      }

      sb.AddConstraint(Operator.Equals, "tag", tagName);
      SqlStatement stmt = sb.GetStatement(true);
      IList<Setting> settingsFound = ObjectFactory.GetCollection<Setting>(stmt.Execute());
      if (settingsFound.Count == 0)
      {
        Setting set = new Setting(tagName, defaultValue);
        set.Persist();
        return set;
      }
      return settingsFound[0];
    }
開發者ID:rndthoughts,項目名稱:ipimpplus,代碼行數:39,代碼來源:TvServiceWebServices.asmx.cs

示例16: Execute

 
        public override void Execute(IDatabase database)
        {
            if (!Table.Columns.Any())
            {
                throw new InvalidOperationException("Cannot create a table with no columns.");
            }

            var sql = new SqlBuilder();
            sql.Append("if not ({0}) begin create table {1} (",
                GetTableExistsSql(database, Table.Name),
                database.FormatTableNameAndEscape(Table.Name));

            var i = 0;
            foreach (var column in Table.Columns)
            {
                var sqlBuilder = new SqlBuilder()
                    .Append(i > 0, ",")
                    .Append(database.Escape(column.Name))
                    .Append(GetColumnSqlType(column, i.ToString()));

                sql.Append(sqlBuilder);
                i++;
            }

            sql.Append("); end;");

            database.RawExecute(sql.ToString());
        }
開發者ID:asgerhallas,項目名稱:HybridDb,代碼行數:28,代碼來源:CreateTable.cs

示例17: Init

 
        public void Init()
        {
            GentleSettings.CacheObjects = false;
            CacheManager.Clear();
            SqlBuilder sb = new SqlBuilder( StatementType.Delete, typeof(MultiType) );
            Broker.Execute( sb.GetStatement( true ) );
        }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:7,代碼來源:TestMultiType.cs

示例18: BuildForm

 
 public Form BuildForm(SqlBuilder Builder, FormLayouts FormLayout = FormLayouts.Vertical, SectionLayouts SectionLayout = SectionLayouts.VerticalTwoColumns)
 {
     Form form = new Form();
     form.FormLayout = FormLayout;
     for (int i = 0; i < Builder.Tables.Count; i++)
     {
         FormSection section = new FormSection() { SectionLayout = SectionLayout };
         Table table = Builder.Tables[i];
         MetadataTable mt = Builder.Metadata.FindTable(table.FullName);
         // section.Legend = StringMap.Default.GetText(SqlBuilder.DefaultCulture.LCID, mt.Fullname, mt.Name);
         section.Legend = mt.DisplayName;
         string TableName = mt.Fullname;
         if (i == 0)
         {
             form.TitleColumn = mt.GuessTitleColumn();
         }
         foreach (Field field in table.FieldList)
         {
             string name = field.Name;
             MetadataColumn mc;
             if (mt.Columns.TryGetValue(name, out mc))
             {
                 MetadataColumn includedFrom = mt.Columns.Values.FirstOrDefault(x => x.IncludeColumns != null && x.IncludeColumns.Contains(field.Alias ?? field.Name));
                 BuildField(mc, TableName, field.Alias, section, includedFrom, i > 0);
             }
         }
         if (section.Fields.Count > 0)
         {
             form.Sections.Add(section);
         }
     }
     form.Sections[0].Fields.Insert(0, new FormField() { Name = "__TABLE", ID = "__TABLE", FieldType = FieldTypes.Input, InputType = InputTypes.text, IsHidden = true });
     return form;
 }
開發者ID:pmarflee,項目名稱:TinySql,代碼行數:34,代碼來源:FormFactory.cs

示例19: TestSqlBuilder

 
 public void TestSqlBuilder()
 {
     TestModel model = new TestModel();
     SqlBuilder builder = new SqlBuilder();
     string expected = "SELECT OrderType, OrderNbr FROM SOOrder";
     string result = builder.Select(model).ToString();
     Assert.IsTrue(expected.ToLower().Trim() == result.ToLower().Trim());
 }
開發者ID:hdanh,項目名稱:HDanh.Framework,代碼行數:8,代碼來源:UnitTest1.cs

示例20: Init

 
        public void Init()
        {
            GentleSettings.CacheObjects = false;
            CacheManager.Clear();
            // make sure table is empty before we start
            SqlBuilder sb = new SqlBuilder( StatementType.Delete, typeof(PropertyHolder) );
            Broker.Execute( sb.GetStatement( true ) );
        }
開發者ID:arangas,項目名稱:MediaPortal-1,代碼行數:8,代碼來源:TestPropertyHolder.cs


注:本文中的SqlBuilder類示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

 

 

转 https://vimsky.com/zh-tw/examples/detail/csharp-ex---SqlBuilder---class.html

标签:SqlBuilder,示例,C#,builder,代碼,var,new
来源: https://www.cnblogs.com/wl-blog/p/16290638.html