前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# 执行SQL脚本文件

C# 执行SQL脚本文件

作者头像
跟着阿笨一起玩NET
发布2018-09-18 15:21:24
1.7K0
发布2018-09-18 15:21:24
举报

本文转载:http://www.cnblogs.com/anjou/archive/2010/08/10/1796563.html

代码语言:javascript
复制
代码 
public static int ExecuteSqlScript(string sqlFile)
{
    int returnValue = -1;
    int sqlCount = 0, errorCount = 0;
    if (!File.Exists(sqlFile))
    {
        Log.WriteLog(string.Format("sql file not exists!", sqlFile));
        return -1;
    }
    using (StreamReader sr = new StreamReader(sqlFile))
    {
        string line = string.Empty;
        char spaceChar = ' ';
        string newLIne = "\r\n", semicolon = ";";
        string sprit = "/", whiffletree = "-";               
        string sql = string.Empty;
        do
        {
            line = sr.ReadLine();
            // 文件结束
            if (line == null) break;
            // 跳过注释行
            if (line.StartsWith(sprit) || line.StartsWith(whiffletree)) continue;
            // 去除右边空格
            line = line.TrimEnd(spaceChar);
            sql += line;
            // 以分号(;)结尾,则执行SQL
            if (sql.EndsWith(semicolon))
            {
                try
                {
                    sqlCount++;
                    SqlHelper.ExecuteNonQuery(sql, null);
                }
                catch (Exception ex)
                {
                    errorCount++;
                    Log.WriteLog(sql +  newLIne + ex.Message);  
                }                        
                sql = string.Empty;
            }
            else
            {
                // 添加换行符
                if(sql.Length > 0) sql += newLIne;
            }
        } while (true);
    }
    if (sqlCount > 0 && errorCount == 0)
        returnValue = 1;
    if (sqlCount == 0 && errorCount == 0)
        returnValue = 0;
    else if (sqlCount > errorCount && errorCount > 0)
        returnValue = -1;
    else if (sqlCount == errorCount)
        returnValue = -2;
    return returnValue;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-06-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档