91网首页-91网页版-91网在线观看-91网站免费观看-91网站永久视频-91网站在线播放

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網站管理員

C#中優(yōu)化SQL語句格式化的方法

admin
2023年10月30日 15:30 本文熱度 1867

在C#中,我們通常使用System.Data.SqlClient命名空間下的SqlCommand和SqlConnection類來與SQL Server數據庫進行交互。在這個過程中,使用參數化查詢是最佳實踐,因為它不僅可以防止SQL注入攻擊,還可以提高代碼的可讀性和可維護性。下面是一個詳細的步驟和代碼示例:

1、首先,你需要建立一個數據庫連接。要實現(xiàn)這一點,你需要創(chuàng)建一個SqlConnection對象,并使用數據庫的連接字符串初始化它。這個連接字符串通常包含數據庫服務器的位置、數據庫名稱、以及登陸服務器的用戶名和密碼。

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

SqlConnection connection = new SqlConnection(connectionString);

2、接下來,你需要打開到數據庫的連接。你可以使用connection.Open()方法來實現(xiàn)這一點。

connection.Open();

3、然后,你可以創(chuàng)建一個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、之后,你可以執(zhí)行這個命令。你可以使用command.executeReader()方法來執(zhí)行查詢并返回一個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語句,并執(zhí)行查詢。記住,始終避免直接將變量插入查詢字符串,這可以幫助防止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是一款針對中小制造業(yè)的專業(yè)生產管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內大量中小企業(yè)的青睞。
點晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業(yè)務管理,結合碼頭的業(yè)務特點,圍繞調度、堆場作業(yè)而開發(fā)的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點晴WMS倉儲管理系統(tǒng)提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統(tǒng),標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 精品97在线观看 | 精品无人区 | 国产精品最新高清 | 日本在线观 | 欧美日韩精品久 | 91成人国产网| 欧洲美妇艹 | 午夜一区| 欧美日韩一区免费 | 无码精品国产第一区二区 | 91福利在线网 | 区区三区蜜桃 | 国产79在| 97午夜理伦 | 三级特黄60分钟在 | 国产玉足免费观看 | 97免费无| 成人日本在线观看 | 不卡免费 | 国产欧美一区二区精 | 91午夜福利电影 | 国产一区欧美亚洲 | 国产一区丝袜在线 | 欧美日韩另 | 成人午夜三 | 日韩精品在线观看 | 精品成人九九九 | 伦理电影网 | 噼里啪啦 | 日本特级婬片免费 | 欧美日韩中文有 | 午夜视频网站 | 国产在线观看免费 | 午夜日韩在线观看 | 日本黄页 | 国产末成年女噜噜 | 日韩VA在线 | 日韩老熟女一区二区 | 国产在线成人91 | 国产欧美网址 | 国产男女爽爽爽免 |