2013-08-16 80 views
1

我有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脚本。

这可能吗?我怎样才能做到这一点?

任何评论都将是很有益的,并感激..

回答

3

使用

using Microsoft.SqlServer.Management.Common; 
using Microsoft.SqlServer.Management.Smo; 

你可以做如下

SqlConnection conn = new SqlConnection(sqlConnectionString); 
Server server = new Server(new ServerConnection(conn)); 
server.ConnectionContext.ExecuteNonQuery(script); 
0

这可能吗?我怎样才能做到这一点?

如果你有数据库和脚本文件执行,那么是的,这是可能的。

首先,您需要获取所选数据库的连接字符串并建立连接。然后你可以使用SMO对象来执行你的批量查询。

string connectionString = "YourConnectionString"; 
//make a sql connection 
using (var sqlConnection = new SqlConnection(connectionString)) 
    { 
     var serverConnection = new ServerConnection(sqlConnection); 
     var server = new Server(serverConnection); 
     server.ConnectionContext.ExecuteNonQuery(textentry); 
    } 

注意:您应该考虑使用正常的查询,如果您还没有批statments执行。正如你可以使用smo对象进入许多问题

+0

但脚本会在选定的数据库中执行吗?因为一些脚本不能在master数据库中执行。我有两个脚本一个用于master数据库,另一个用于其他数据库。如果我选​​择master数据库,它应该在master数据库中执行。如果我选择了其他的,那么它应该在我选择的数据库中执行。通过上面的代码,这是否可能? –

+0

@VysakhVenugopal你需要连接到你选择的数据库。根据选定的数据库构建连接字符串 – Ehsan

+0

我对所有数据库都有相同的连接字符串。我有一个凭证登录master.I通常用于脚本执行。所以,在这里我也会使用相同的,但是需要在组合框1中指定数据库时执行脚本。 –