' \'附近的语法不正确

时间:2015-05-11 09:02:44

标签: c# sql

我需要编写一个程序,在特定的路径位置迭代几个SQL脚本并执行它们。进度条会在进度条上增加,我仍然需要这样做,进度将显示在TextBox上。运行程序时,我收到以下错误:

  

' \'

附近的语法不正确

代码如下:

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 个答案:

答案 0 :(得分:4)

这是问题所在:

cmd.CommandText = fl.ToString();

您将文件名作为命令文本传递,而不是文本本身。您已在此处加载文字:

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

...但后来没有使用那个变量。我怀疑你想要:

cmd.CommandText = scripts;

请注意,使用File.ReadAllText比创建新的FileInfo等要简单得多:

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

另请注意,对于usingSqlConnection,您应该有SqlCommand个语句,以便在发生异常时正确关闭它们。