无法使用数据库名称SQL Server&的参数创建数据库。 C#

时间:2018-05-18 15:12:46

标签: c# sql-server database

我正在尝试使用此代码:

map_and_batch()

我在var connString = "Server=localhost\\SQLEXPRESS;Integrated Security = SSPI; database = master"; string cmdText = "CREATE DATABASE @userDatabase"; using (var sqlConnection = new SqlConnection(connString)) { using (var sqlCmd = new SqlCommand(cmdText, sqlConnection)) { sqlCmd.Parameters.Add("@userDatabase", System.Data.SqlDbType.NVarChar).Value = databaseName; sqlConnection.Open(); sqlCmd.ExecuteNonQuery(); } } 上收到错误:

  

'@ userDatabase'附近的语法不正确

但是,当我使用动态SQL代码添加数据库时,我没有错误,查询运行完美(我听说这会很危险)。

1 个答案:

答案 0 :(得分:0)

您可以创建动态查询来执行此操作。

private void SetupDatabase(string dbFolder, string dbName)
{
  if (Directory.Exists(String.Format("{0}\\db", dbFolder)) == false)
  {
    Directory.CreateDirectory(String.Format("{0}\\db", dbFolder));
  }
  if (File.Exists(String.Format("{0}\\db\\{1}_Data.mdf", dbFolder, dbName)) == false)
  {
    ExecuteQuery(
      "master",
      String.Format("CREATE DATABASE {1} ON PRIMARY (NAME = {1}_Data, FILENAME = '{0}\\db\\{1}_Data.mdf', SIZE = 2MB, FILEGROWTH = 10%) LOG ON (NAME = {1}_Log, FILENAME = '{0}\\db\\{1}_Log.ldf', SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 10%)", dbFolder, dbName));
  }
}

private void ExecuteQuery(
  string db,
  string query)
{
  SqlConnection connection = null;
  try
  {
    connection = new SqlConnection(string.Format(connectionString, db));
    connection.Open();

    // Creates DB
    using (SqlCommand command = new SqlCommand(query, connection))
    {
      command.ExecuteNonQuery();
    }
  }
  catch (Exception ex)
  {
    throw ex;
  }
  finally
  {
    connection.Close();
  }
}