C# 靠近'的语法不正确\';
我需要编写一个程序,在特定的路径位置迭代几个SQL脚本并执行它们。进度将在进度条上递增,我仍然需要这样做,并且进度将显示在C# 靠近'的语法不正确\';,c#,sql,C#,Sql,我需要编写一个程序,在特定的路径位置迭代几个SQL脚本并执行它们。进度将在进度条上递增,我仍然需要这样做,并且进度将显示在文本框中。运行该程序时,我遇到以下错误: “\”附近的语法不正确 代码如下: public void runScripts() { int lc = System.IO.Directory.GetFiles(this.sc, "*.*", System.IO.SearchOption.AllDirectories).Length; this.pgbCopyPr
文本框中。运行该程序时,我遇到以下错误:
“\”附近的语法不正确
代码如下:
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();
}
}
}
这就是问题所在:
cmd.CommandText = fl.ToString();
您将文件名作为命令文本传递,而不是文本本身。您正在此处加载文本:
string scripts = file.OpenText().ReadToEnd();
。。。但是不使用这个变量。我怀疑你想要:
cmd.CommandText = scripts;
请注意,使用将比创建新的FileInfo
等要简单得多:
string sql = File.ReadAllText(@"\\" + this.sc);
还请注意,您应该让为SqlConnection
和SqlCommand
使用语句,以便在引发异常时正确关闭它们。这就是问题所在:
cmd.CommandText = fl.ToString();
您将文件名作为命令文本传递,而不是文本本身。您正在此处加载文本:
string scripts = file.OpenText().ReadToEnd();
。。。但是不使用这个变量。我怀疑你想要:
cmd.CommandText = scripts;
请注意,使用将比创建新的FileInfo
等要简单得多:
string sql = File.ReadAllText(@"\\" + this.sc);
还请注意,您应该为SqlConnection
和SqlCommand
使用语句,以便在引发异常时正确关闭它们。哪一行显示语法错误?它实际上是编译时错误还是异常?cmd.ExecuteNonQuery();line@naheiwProg啊,你能更新你的问题,然后请提及这是一个运行时错误吗?(不清楚)因此也不清楚错误发生在哪一行。tnxI不认为文件路径是正确的SQL命令。哪一行显示语法错误?它实际上是编译时错误还是异常?cmd.ExecuteNonQuery();line@naheiwProg啊,你能更新你的问题,然后请提及这是一个运行时错误吗?(不清楚)因此也不清楚错误发生在哪一行。tnxI不认为文件路径是正确的SQL命令。