C#使用脚本来创建数据库

时间:2012-05-08 06:21:20

标签: c# sql sql-server

我喜欢在下面的代码中使用FILENAME的参数,而不是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.");
   }
}

2 个答案:

答案 0 :(得分:2)

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

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();
    }

答案 1 :(得分: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#代码读取此文件,并将XXXMDFXXX的值替换为参数值N'D:\Work\DBLocation\Files\Employee.mdf'和XXXLDFXXX,将其替换为第二个参数值N'D:\Work\DBLocation\Files\Employee.ldf'

替换完成后

将新文件保存在新位置并使用新名称dbMainCreate.sql

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

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