2015-05-11 104 views
0

我需要編寫一個程序,該程序在特定路徑位置遍歷幾個SQL腳本並執行它們。進度條會在進度條上增加,我仍然需要這樣做,並且進度將顯示在TextBox上。運行程序時,我得到了以下錯誤:''附近的語法不正確

Incorrect syntax near '\'.

的代碼如下:

public void runScripts() 
{ 
    int lc = System.IO.Directory.GetFiles(this.sc, "*.*", System.IO.SearchOption.AllDirectories).Length; 
    this.pgbCopyProgress.Maximum = lc; 
    DirectoryInfo dir = new DirectoryInfo(this.sc); 
    DirectoryInfo[] dirs = dir.GetDirectories(); 

    if (!dir.Exists) 
    { 
     throw new DirectoryNotFoundException(
       "Source directory does not exist or could not be found: " 
       + this.sc); 
    } 

    // Get the scripts in the directory and run them 
    FileInfo[] files = dir.GetFiles(); 
    foreach (FileInfo file in files) 
    { 
     try 
     { 
      string sqlConnectionString = "Data Source=(local);Initial Catalog=Wiehan_Deployer;Integrated Security=True"; 
      string f = this.sc; 
      f = f + @"\" + file; 
      FileInfo fl = new FileInfo(f); 
      string scripts = file.OpenText().ReadToEnd(); 
      SqlConnection con = new SqlConnection(sqlConnectionString); 
      con.Open(); 
      SqlCommand cmd = new SqlCommand(); 
      cmd.Connection = con; 
      cmd.CommandText = fl.ToString(); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 
      txtEvents.Text += "\nScript executed successfully." + f; 
      lc = System.IO.Directory.GetFiles(this.sc, "*.*", System.IO.SearchOption.AllDirectories).Length; 
      this.pgbCopyProgress.Value = lc; 
      this.pgbCopyProgress.Update(); 
      this.pgbCopyProgress.Refresh(); 
     } 
     catch (Exception ex) 
     { 
      txtEvents.Text += ex.Message + "\r\n" ; 
      txtEvents.Update(); 
      txtEvents.Refresh(); 
     } 
    } 
} 
+1

哪一行顯示語法錯誤? – Thomas

+0

而且它*實際上是一個編譯時錯誤還是一個異常? –

+0

cmd.ExecuteNonQuery();行 – naheiwProg

回答

4

這就是問題所在:

cmd.CommandText = fl.ToString(); 

你在文件名作爲傳遞命令文本,而不是文本本身。你裝載這裏是正文:

string scripts = file.OpenText().ReadToEnd(); 

...但隨後沒有使用這個變量。我懷疑你想要的東西:

cmd.CommandText = scripts; 

注意,使用File.ReadAllText會比創建簡單得多了新FileInfo等:

string sql = File.ReadAllText(@"\\" + this.sc); 

另外請注意,您應該爲您的SqlConnectionSqlCommandusing語句,以如果拋出異常,請正確關閉它們。

+0

謝謝@JonSkeet – naheiwProg