1

我需要为数据表中的每一行附加一个 Sqlquery。我有 36 列,并且根据每列的数据类型,我需要附加 sqlquery。任何人都可以建议我这样做的有效方法。它是不好的编码方式吗? “+”运算符在追加之间追加文本?

Following is my code.

 query ="INSERT INTO MASTERPI (tag,instrumenttag)");
 query += "VALUES ('" + createTagRow["tag"].ToString() + "','" + createTagRow["instrumenttag"].ToString() + "'");

谢谢,维克斯

4

3 回答 3

5

如果您已经在使用 aStringBuilder那么同时使用常规字符串连接是有害的。您正在否定该课程的一半效用StringBuilder。不要这样做。使用StringBuilder.Append排他的方法并摆脱那些+陈述。

我还认为所有这些createTagRow(...).ToString()电话都是浪费的。里面的东西正在做将这些元素序列化为字符串的工作,所以你实际上做了两次工作,创建字符串然后附加它。如果您可以将StringBuilder自身传递给那些createTagRow调用,那也不会那么……可怕。

实际上,在第二次查看时,似乎这段代码正在构建一个 SQL 查询。 参数化该查询 NOW。没有理由。这样,您甚至无需担心string.Formatvs. StringBuildervs. concatenation,DB 库将为您处理这一切。

于 2010-02-22T06:52:25.147 回答
0

如果您使用String.Format构建查询的每一行,并利用其占位符语法将行对象中的数据插入到查询文本中,您的代码可能会更具可读性。

于 2010-02-22T06:51:15.333 回答
0

如前所述,您应该考虑两种可能性:

  1. Aaronaught:参数化该查询
  2. 如果您需要完全控制语句字符串,您应该查看.FormatWith 扩展并将您的不同块重构为类,从而返回所需的部分。

一个小例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var columns = new CommaSeparated();

            columns.Add("tag");
            columns.Add("instrumenttag");
            columns.Add("pointsource");
            columns.Add("pointtype");
            columns.Add("dataowner");
            columns.Add("dataaccess");
            columns.Add("location1");
            columns.Add("location2");
            columns.Add("location3");
            columns.Add("location4");
            columns.Add("location5");
            columns.Add("...");


            var values = new CommaSeparated();

            values.EncloseEachElementWith = "'";
            values.Add(createTagRow["tag"].ToString());
            values.Add(createTagRow["instrumenttag"].ToString());
            values.Add(createTagRow["pointsource"].ToString());
            values.Add(createTagRow["pointtype"].ToString());
            values.Add(createTagRow["dataowner"].ToString());
            values.Add(createTagRow["dataaccess"].ToString());
            values.Add(createTagRow["location1"].ToString());
            values.Add(createTagRow["location2"].ToString());
            values.Add(createTagRow["location3"].ToString());
            values.Add(createTagRow["location4"].ToString());
            values.Add(createTagRow["location5"].ToString());
            values.Add(createTagRow["..."].ToString());

            //INSERT INTO MASTERPI ({columns}) values ({values})
            var query = "INSERT INTO MASTERPI ({columns}) values ({values})".FormatWith(new { columns, values });

            Console.WriteLine(query);
            Console.ReadKey();
        }
    }

    public class CommaSeparated : List<string>
    {
        public CommaSeparated()
            : base()
        {
            EncloseEachElementWith = String.Empty;
        }

        public override string ToString()
        {
            var elements = this.Select(element => String.Format("{0}{1}{0}", EncloseEachElementWith, element));

            return String.Join(", ", elements.ToArray());
        }

        public string EncloseEachElementWith { get; set; }
    }

    public static class StringExtensions
    {
        public static string FormatWith(this string format, object source)
        {
            return FormatWith(format, null, source);
        }

        public static string FormatWith(this string format, IFormatProvider provider, object source)
        {
            if (format == null)
                throw new ArgumentNullException("format");

            Regex r = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+",
              RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

            List<object> values = new List<object>();
            string rewrittenFormat = r.Replace(format, delegate(Match m)
            {
                Group startGroup = m.Groups["start"];
                Group propertyGroup = m.Groups["property"];
                Group formatGroup = m.Groups["format"];
                Group endGroup = m.Groups["end"];

                values.Add((propertyGroup.Value == "0")
                  ? source
                  : DataBinder.Eval(source, propertyGroup.Value));

                return new string('{', startGroup.Captures.Count) + (values.Count - 1) + formatGroup.Value
                  + new string('}', endGroup.Captures.Count);
            });

            return string.Format(provider, rewrittenFormat, values.ToArray());
        }
    }
}
于 2010-02-22T07:53:36.077 回答