我有2种形式,首先收集数据源,数据库名称,用户名和密码等细节。第二种形式收集要执行的sql脚本文件和要连接到的数据库名称。c#执行sql脚本
我想要实现的是我应该能够在所选数据库中执行sql脚本文件。
在第二形式中使用的代码是这样的:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
string sel = comboBox1.SelectedItem.ToString(); //Here "sel" is the database selected
if (sel == "master")
{
comboBox2.Items.Clear();
//Selects a default file
DirectoryInfo dinfo = new DirectoryInfo(@"D:\Testpgm");
FileInfo[] Files = dinfo.GetFiles("master.sql", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
comboBox2.Items.Add(file.Name);
}
}
else
{
comboBox2.Items.Clear();
//Selects a default file
DirectoryInfo dinfo = new DirectoryInfo(@"D:\Testpgm");
FileInfo[] Files = dinfo.GetFiles("dbscript.sql", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
comboBox2.Items.Add(file.Name);
}
}
}
而在组合框2中使用的代码是:
private void comboBox2_TextChanged(object sender, EventArgs e)
{
string textsel = comboBox2.SelectedItem.ToString(); //textsel is used to select the sql file selected
if (textsel == "master.sql")
{
richTextBox1.Clear();
//Read the selected sql file and display it in richtextbox
System.IO.StreamReader myFile = new System.IO.StreamReader(@"D:\Testpgm\master.sql");
string textentry = myFile.ReadToEnd();
richTextBox1.AppendText(textentry);
}
else
{
richTextBox1.Clear();
//Read the selected sql file and display it in richtextbox
System.IO.StreamReader myFile = new System.IO.StreamReader(@"D:\Testpgm\dbscript.sql");
string textentry = myFile.ReadToEnd();
richTextBox1.AppendText(textentry);
}
}
现在,我要连接到哪个我所选择的数据库在组合框1中,然后通过单击按钮,优化包含在组合框2中选择的sql文件中的sql脚本。
这可能吗?我怎样才能做到这一点?
任何评论都将是很有益的,并感激..
但脚本会在选定的数据库中执行吗?因为一些脚本不能在master数据库中执行。我有两个脚本一个用于master数据库,另一个用于其他数据库。如果我选择master数据库,它应该在master数据库中执行。如果我选择了其他的,那么它应该在我选择的数据库中执行。通过上面的代码,这是否可能? –
@VysakhVenugopal你需要连接到你选择的数据库。根据选定的数据库构建连接字符串 – Ehsan
我对所有数据库都有相同的连接字符串。我有一个凭证登录master.I通常用于脚本执行。所以,在这里我也会使用相同的,但是需要在组合框1中指定数据库时执行脚本。 –