2

我喜欢FILENAME在下面的代码中使用参数 for,而不是 N'D:\DBName.mdf' 和 N'D:\DBName.ldf'。

如何在.sql文件中更改它以及如何使用参数从 C# 调用它?谢谢。

SQL脚本:

CREATE DATABASE [DBName] ON  PRIMARY 
( NAME = N'DBName', FILENAME = N'D:\DBName.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'DBName_log', FILENAME = N'D:\DBName.ldf' , SIZE = 3456KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
END

C# 代码

string appPathDB = Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.mdf";
string appPathLog = Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName_log.ldf";

private void CreateDatabase()
{
   string connection = "Data Source=localhost;Initial Catalog=master;User ID=sa;Password=abcd1234";
   FileInfo file = new FileInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.sql");
   string script = file.OpenText().ReadToEnd();
   ExecSql(script, connection, "DBName");
   file.OpenText().Close();
}

public void ExecSql(string sql, string connectionString, string dataBaseNameToPrepend)
{
   using (SqlConnection conn = new SqlConnection(connectionString))
   {
      conn.Open();
      Server server = new Server(new ServerConnection(conn));
      server.ConnectionContext.ExecuteNonQuery(sql);
      server.ConnectionContext.Disconnect();
      server.ConnectionContext.ExecuteNonQuery(sql);
      MessageBox.Show("DB Uploaded.");
   }
}
4

2 回答 2

3

对您的脚本文件进行以下更改并保存。

CREATE DATABASE [DBName] ON  PRIMARY 
( NAME = N'DBName', FILENAME = N'DB_NAME_MDF' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'DBName_log', FILENAME = N'DB_NAME_LDF' , SIZE = 3456KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
END

将以下行添加到您的代码中。

private void CreateDatabase()
    {
        string connection = "Data Source=localhost;Initial Catalog=master;User ID=sa;Password=abcd1234";
        FileInfo file = new FileInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.sql");
        string script = file.OpenText().ReadToEnd();
        script = script.Replace("DB_NAME_MDF", appPathDB).Replace("DB_NAME_LDF", appPathLog);
        ExecSql(script, connection, "DBName");
        file.OpenText().Close();
    }
于 2012-05-08T06:41:32.140 回答
1

我认为有不同的方法可以解决这个问题。

但根据我的说法,在这里找到工作的简单方法是

创建一个文件说 dbcreate.sql

CREATE DATABASE [DBName] ON  PRIMARY 
( NAME = N'DBName', FILENAME = XXXMDFXXX , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'DBName_log', FILENAME = XXXLDFXXX , SIZE = 3456KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
END

将此文件保存在应用程序中的某个位置,并在 C# 代码中读取此文件,并将 XXXLDFXXX 的值替换XXXMDFXXX为您的参数值N'D:\Work\DBLocation\Files\Employee.mdf',并将 XXXLDFXXX 替换为您的第二个参数值N'D:\Work\DBLocation\Files\Employee.ldf'

替换完成后将新文件保存在新位置并使用新名称说 dbMainCreate.sql

保存成功后,按照您的代码使用新参数创建数据库。

注意:在存储新文件之前,您可以检查文件是否已在该位置可用,如果是,则删除现有文件,然后保存。您还可以将文件移动或复制到另一个位置以保持版本控制。

于 2012-05-08T06:37:22.520 回答