Create .mdf/.sdf database dynamically

后端 未结 7 772
萌比男神i
萌比男神i 2020-12-29 11:21

How can I with \"code\" create a new .mdf/.sdf database?

I\'ve tried this: http://support.microsoft.com/kb/307283

All it does is fail on the ConnectionString

7条回答
  •  时光说笑
    2020-12-29 12:03

    public static void CreateSqlDatabase(string filename)
    {
        string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
        using (var connection = new System.Data.SqlClient.SqlConnection(
            "Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText =
                    String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
                command.ExecuteNonQuery();
    
                command.CommandText =
                    String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
                command.ExecuteNonQuery();
            }
        }
    }
    

    Change Catalog=tempdb to Catalog=master, its good worked

    Sample use:

    var filename = System.IO.Path.Combine("D:\\", "testdb.mdf");
    if (!System.IO.File.Exists(filename))
    {
        CreateSqlDatabase(filename);
    }
    

提交回复
热议问题