C# 執行SQL腳本文件


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

 

代碼 
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  ==  nullbreak;
             // 跳過注釋行
             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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM