C#实现格式化SQL语句的示例代码

 更新时间:2023年08月23日 10:32:05   作者:Csharp 小记  
这篇文章主要为大家详细介绍了C#如何实现格式化SQL语句的功能,文中的示例代码简洁易懂,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下

前言

本来想自己去实现这个功能的,后来吧,经过一番深思熟虑,我觉得还是太麻烦了。所以,打开Github,搜索现成的轮子。。。

即便是在GIithub上,关于用c#来做这个功能的我也没找到几个(也可能是我搜索姿势不太标准)。

说实话,里面的代码我也没有去研究,但大致就是把SQL语句经过一系列分析后,转换成HTM文件,然后用WebBrowser加载出来。看起来还是比较简单的,但是作者写的比较复杂,使我丧失了仔细研读的耐心。。。

不过基于上面这种思想的话,我倒是觉得大可不必非要找C#语言的了,也可以同步看下js的,反正最后是加载html,直接拿过来用可能也比较简单。

原作者的这个工具写的比较完善,v2版本用了dev控件做了美化,而且是实时(定时)检测sql语句进行格式化。如下:

我就做的比较简单了,页面还是仿照了原作者的布局,但是去掉了一些代码,为了更简单的调用。。。

可以直接把BaiSqlFormatLib.dll拿来调用,或者集成源代码到项目中。

实现功能

输入SQL语句进行格式化

开发环境

开发工具:Visual Studio 2013

.NET Framework版本:4.5

实现代码

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 on中on 条件换行
                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);
        }
        #endregion
        #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

实现效果

到此这篇关于C#实现格式化SQL语句的示例代码的文章就介绍到这了,更多相关C#格式化SQL语句内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 带着问题读CLR via C#(笔记一)CLR的执行模型

    带着问题读CLR via C#(笔记一)CLR的执行模型

    CLR (Common Language Runtime) 是一个可以由多种编程语言使用的“运行时”。
    2013-04-04
  • C#中File和FileStream的简单介绍和用法

    C#中File和FileStream的简单介绍和用法

    这篇文章主要给大家介绍了关于C#中File和FileStream用法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • C#从XmlDocument提取完整字符串的方法

    C#从XmlDocument提取完整字符串的方法

    文章介绍了两种生成格式化XML字符串的方法,方法一使用`XmlDocument`的`OuterXml`属性,但输出的XML字符串不带格式,可读性差,方法二利用`XmlWriterSettings`控制格式,并通过`MemoryStream`作为输出流,可以自定义编码,如UTF-8,感兴趣的朋友跟随小编一起看看吧
    2025-02-02
  • Unity Undo实现原理和使用方法详解

    Unity Undo实现原理和使用方法详解

    本文将详细介绍Unity Undo实现原理和使用方法,并提供多个使用例子,帮助开发者更好地理解和应用该功能,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • 基于c#用Socket做一个局域网聊天工具

    基于c#用Socket做一个局域网聊天工具

    目前基于Internet的即时聊天工具已经做的非常完美,本文介绍了基于c#用Socket做一个局域网聊天工具,有需要的朋友可以看一下。
    2016-10-10
  • 如何解决hash冲突

    如何解决hash冲突

    上篇文章 为什么哈希存取比较快?使用它需要付出什么代价 只是简单介绍了使用hash所带来的利与弊。并未涉及hash的技术细节,本文则着重学习一下如何解决哈希编址的冲突问题。
    2016-06-06
  • 基于C#设计一个带导航菜单的主界面

    基于C#设计一个带导航菜单的主界面

    这篇文章主要为大家详细介绍了如何基于C#设计一个带导航菜单的主界面,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-04-04
  • 使用C#发送Http请求实现模拟登陆实例

    使用C#发送Http请求实现模拟登陆实例

    本文主要介绍了使用C#发送Http请求实现模拟登陆实例,模拟登陆的原理简单,想要了解的朋友可以了解一下。
    2016-10-10
  • C#计算程序执行过程花费时间的方法

    C#计算程序执行过程花费时间的方法

    这篇文章主要介绍了C#计算程序执行过程花费时间的方法,涉及C#简单的时间运算技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-09-09
  • 用C#将图片保存至Oracle BLOB字段中的方法

    用C#将图片保存至Oracle BLOB字段中的方法

    这篇文章主要介绍了用C#将图片保存至Oracle BLOB字段中的方法, 依靠ImageViewer库进行操作,需要的朋友可以参考下
    2015-07-07

最新评论