LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#中优化SQL语句格式化的方法

admin
2023年10月30日 15:30 本文热度 503

在C#中,我们通常使用System.Data.SqlClient命名空间下的SqlCommand和SqlConnection类来与SQL Server数据库进行交互。在这个过程中,使用参数化查询是最佳实践,因为它不仅可以防止SQL注入攻击,还可以提高代码的可读性和可维护性。下面是一个详细的步骤和代码示例:

1、首先,你需要建立一个数据库连接。要实现这一点,你需要创建一个SqlConnection对象,并使用数据库的连接字符串初始化它。这个连接字符串通常包含数据库服务器的位置、数据库名称、以及登陆服务器的用户名和密码。

string connectionString = "Data Source=serverName;Initial Catalog=databaseName;User ID=username;Password=password";

SqlConnection connection = new SqlConnection(connectionString);

2、接下来,你需要打开到数据库的连接。你可以使用connection.Open()方法来实现这一点。

connection.Open();

3、然后,你可以创建一个SqlCommand对象,将你的SQL查询和所需的参数作为输入。注意,应避免直接将变量插入查询字符串,因为这可能使你的程序暴露于SQL注入攻击。取而代之的是,你应该使用SqlParameter对象来添加参数,然后将其添加到SqlCommand对象的参数集合中。

string sql = "select * from table where column = @param";

SqlCommand command = new SqlCommand(sql, connection);

command.Parameters.AddWithValue("@param", yourVariable);

4、之后,你可以执行这个命令。你可以使用command.executeReader()方法来执行查询并返回一个SqlDataReader对象,这个对象包含查询结果。

SqlDataReader reader = command.executeReader();

5、最后,你需要通过SqlDataReader对象来读取查询结果。你可以使用Read()方法来读取每一行数据。

while (reader.Read())

{

    Console.WriteLine(reader["columnName"]);

}

所以,完整的代码示例可能如下所示:

string connectionString = "Data Source=serverName;Initial Catalog=databaseName;User ID=username;Password=password";

using (SqlConnection connection = new SqlConnection(connectionString))

{

    connection.Open();
   
string sql = "select * from table where column = @param";

    using (SqlCommand command = new SqlCommand(sql, connection))

    {

        command.Parameters.AddWithValue("@param", yourVariable);

        using (SqlDataReader reader = command.executeReader())

        {

            while (reader.Read())

            {

                Console.WriteLine(reader["columnName"]);

            }

        }

    }

}

这个示例展示了如何在C#中使用参数化查询来格式化SQL语句,并执行查询。记住,始终避免直接将变量插入查询字符串,这可以帮助防止SQL注入攻击。

接下来讲一下如何将SQL语句进行格式化?

先看效果:

直接上代码:

public Form1()

{

    InitializeComponent();

    Init();

}


#region 初始化配置

ISqlTokenizer _tokenizer;

ISqlTokenParser _parser;

ISqlTreeFormatter _formatter;

public void Init()

{

    chk_default.Checked = true;

    _tokenizer = new BaiSqlFormatLib.Tokenizers.TSqlStandardTokenizer();

    _parser = new BaiSqlFormatLib.Parsers.TSqlStandardParser();

}

#endregion

 

#region 格式化

private void textBox1_KeyDown(object sender, KeyEventArgs e)

{

    if (e.KeyData == Keys.F6)

    {

        txt_format.DocumentText = Format(txt_sql.Text);

    }

}

private string Format(string inputSql)

{

    SetFormatter();

    var tokenizedSql = _tokenizer.TokenizeSQL(inputSql, inputSql.Length);

    var parsedSql = _parser.ParseSQL(tokenizedSql);

    string subSqlHtml = _formatter.FormatSQLTree(parsedSql);

    return subSqlHtml;

}

 

/// <summary>

/// 设置格式化属性

/// </summary>

private void SetFormatter()

{

    ISqlTreeFormatter innerFormatter = new BaiSqlFormatLib.Formatters.TSqlStandardFormatter(

    new BaiSqlFormatLib.Formatters.TSqlStandardFormatterOptions

    {

        IndentString = "\\s\\s\\s\\s"//缩进内容

        SpacesPerTab = 4,

        MaxLineWidth = Convert.ToInt32(txt_maxWidth.Text), //单行字符串最大长度

        ExpandCommaLists = !chk_columnNotNewline.Checked,  //false 字段换行

        KeywordAlign = chk_keywordAlign.Checked,     //字段对齐

        TrailingCommas = true,   //true 逗号在字段之后

        SpaceAfterExpandedComma = true,  //true 逗号后追加空格

        ExpandBooleanExpressions = chk_conditionNewline.Checked,  //true 条件换行

        ExpandCaseStatements = chk_expandCase.Checked,      //true case when换行

        ExpandBetweenConditions = chk_expandBetween.Checked,  //true between 换行

        ExpandInLists = chk_expandIn.Checked,   //true in 内容换行

        BreakJoinOnSections = chk_expandOn.Checked, //true join onon 条件换行

        UppercaseKeywords = chk_uppercaseKeywords.Checked, //true 关键字大写

        AllUpper = chk_allUpper.Checked, //true 全部大写

        HTMLColoring = chk_coloring.Checked, //true HTML颜色标记 默认为true

        KeywordStandardization = true,//true 关键字标准化

        NewStatementLineBreaks = 2//新语句换行数

        NewClauseLineBreaks = 1,//遇到关键字 换行数

        AllIndent = chk_allIndent.Checked, //整体缩进一个IndentString

        AsAlign = chk_asAlign.Checked, //true as对齐

        KeywordLengthOfAs = Convert.ToInt32(txt_asMaxWidth.Text)//as字段的最大长度

    });

    _formatter = new BaiSqlFormatLib.Formatters.HtmlPageWrapper(innerFormatter);

}

 

#region 页面配置

private void chk_default_CheckedChanged(object sender, EventArgs e)

{

    if (chk_default.Checked)

    {

        chk_custom.CheckState = CheckState.Unchecked;
        txt_maxWidth.Text = 
"170";

        chk_columnNotNewline.CheckState = CheckState.Unchecked;

        chk_keywordAlign.CheckState = CheckState.Checked;

        chk_conditionNewline.CheckState = CheckState.Checked;

        chk_expandCase.CheckState = CheckState.Checked;

        chk_expandBetween.CheckState = CheckState.Unchecked;

        chk_expandIn.CheckState = CheckState.Unchecked;

        chk_expandOn.CheckState = CheckState.Checked;

        chk_uppercaseKeywords.CheckState = CheckState.Unchecked;

        chk_allUpper.CheckState = CheckState.Unchecked;

        chk_coloring.CheckState = CheckState.Checked;

        chk_allIndent.CheckState = CheckState.Checked;

        chk_asAlign.CheckState = CheckState.Checked;

        txt_asMaxWidth.Text = "35";

        chk_addSemicolon.CheckState = CheckState.Checked;
        txt_maxWidth.Enabled = 
false;

        chk_columnNotNewline.Enabled = false;

        chk_keywordAlign.Enabled = false;

        chk_conditionNewline.Enabled = false;

        chk_expandCase.Enabled = false;

        chk_expandBetween.Enabled = false;

        chk_expandIn.Enabled = false;

        chk_expandOn.Enabled = false;

        chk_uppercaseKeywords.Enabled = false;

        chk_allUpper.Enabled = false;

        chk_coloring.Enabled = false;

        chk_allIndent.Enabled = false;

        chk_asAlign.Enabled = false;

        txt_asMaxWidth.Enabled = false;

        chk_addSemicolon.Enabled = false;

    }

    else

        chk_custom.CheckState = CheckState.Checked;

}

 

private void chk_custom_CheckedChanged(object sender, EventArgs e)

{

    if (chk_custom.Checked)

    {

        chk_default.CheckState = CheckState.Unchecked;

        chk_columnNotNewline.Enabled = true;

        chk_keywordAlign.Enabled = true;

        chk_conditionNewline.Enabled = true;

        chk_expandCase.Enabled = true;

        chk_expandBetween.Enabled = true;

        chk_expandIn.Enabled = true;

        chk_expandOn.Enabled = true;

        chk_uppercaseKeywords.Enabled = true;

        chk_allUpper.Enabled = true;

        chk_coloring.Enabled = true;

        chk_allIndent.Enabled = true;

        chk_asAlign.Enabled = true;

        chk_addSemicolon.Enabled = true;

        txt_maxWidth.Enabled = true;

        txt_asMaxWidth.Enabled = true;

    }

    else

        chk_default.CheckState = CheckState.Checked;

}

#endregion

感兴趣的小伙伴可以自己研究研究。


该文章在 2023/10/30 15:37:08 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved