1

我有两种形式,首先收集数据源、数据库名称、用户名和密码等详细信息。第二种形式收集要执行的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 脚本。

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

任何评论都会非常有帮助和赞赏..

4

2 回答 2

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);
于 2013-08-16T05:49:24.433 回答
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); 
    }

注意:如果您没有要执行的批处理语句,您应该考虑使用普通查询。使用 smo 对象可能会遇到很多问题

于 2013-08-16T05:55:24.017 回答