C#中優(yōu)化SQL語句格式化的方法
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
在C#中,我們通常使用System.Data.SqlClient命名空間下的SqlCommand和SqlConnection類來與SQL Server數(shù)據(jù)庫進(jìn)行交互。在這個過程中,使用參數(shù)化查詢是最佳實(shí)踐,因?yàn)樗粌H可以防止SQL注入攻擊,還可以提高代碼的可讀性和可維護(hù)性。下面是一個詳細(xì)的步驟和代碼示例: 1、首先,你需要建立一個數(shù)據(jù)庫連接。要實(shí)現(xiàn)這一點(diǎn),你需要創(chuàng)建一個SqlConnection對象,并使用數(shù)據(jù)庫的連接字符串初始化它。這個連接字符串通常包含數(shù)據(jù)庫服務(wù)器的位置、數(shù)據(jù)庫名稱、以及登陸服務(wù)器的用戶名和密碼。 string connectionString = "Data Source=serverName;Initial Catalog=databaseName;User ID=username;Password=password"; SqlConnection connection = new SqlConnection(connectionString); 2、接下來,你需要打開到數(shù)據(jù)庫的連接。你可以使用connection.Open()方法來實(shí)現(xiàn)這一點(diǎn)。 connection.Open(); 3、然后,你可以創(chuàng)建一個SqlCommand對象,將你的SQL查詢和所需的參數(shù)作為輸入。注意,應(yīng)避免直接將變量插入查詢字符串,因?yàn)檫@可能使你的程序暴露于SQL注入攻擊。取而代之的是,你應(yīng)該使用SqlParameter對象來添加參數(shù),然后將其添加到SqlCommand對象的參數(shù)集合中。 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對象,這個對象包含查詢結(jié)果。 SqlDataReader reader = command.executeReader(); 5、最后,你需要通過SqlDataReader對象來讀取查詢結(jié)果。你可以使用Read()方法來讀取每一行數(shù)據(jù)。 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(); 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#中使用參數(shù)化查詢來格式化SQL語句,并執(zhí)行查詢。記住,始終避免直接將變量插入查詢字符串,這可以幫助防止SQL注入攻擊。 接下來講一下如何將SQL語句進(jìn)行格式化? 先看效果: 直接上代碼: 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> /// 設(shè)置格式化屬性 /// </summary> private void SetFormatter() { ISqlTreeFormatter innerFormatter = new BaiSqlFormatLib.Formatters.TSqlStandardFormatter( new BaiSqlFormatLib.Formatters.TSqlStandardFormatterOptions { IndentString = "\\s\\s\\s\\s", //縮進(jìn)內(nèi)容 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 內(nèi)容換行 BreakJoinOnSections = chk_expandOn.Checked, //true join on中on 條件換行 UppercaseKeywords = chk_uppercaseKeywords.Checked, //true 關(guān)鍵字大寫 AllUpper = chk_allUpper.Checked, //true 全部大寫 HTMLColoring = chk_coloring.Checked, //true HTML顏色標(biāo)記 默認(rèn)為true KeywordStandardization = true,//true 關(guān)鍵字標(biāo)準(zhǔn)化 NewStatementLineBreaks = 2, //新語句換行數(shù) NewClauseLineBreaks = 1,//遇到關(guān)鍵字 換行數(shù) AllIndent = chk_allIndent.Checked, //整體縮進(jìn)一個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; 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; 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 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |