Skip to content

Commit

Permalink
Add method to determine if database exists
Browse files Browse the repository at this point in the history
+semver:minor
  • Loading branch information
chadly committed Jul 26, 2017
1 parent 36a4c7a commit b6f3fdd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Database.cs
Expand Up @@ -65,6 +65,22 @@ string[] ParseScript(string script)
return goEx.Split(script).Where(c => !goEx.IsMatch(c) && !String.IsNullOrWhiteSpace(c)).ToArray();
}

public bool Exists(string connectionString)
{
var builder = new SqlConnectionStringBuilder(connectionString);

string database = builder.InitialCatalog;
builder.InitialCatalog = "";

int count;
using (var conn = new SqlConnection(builder.ToString()))
{
count = conn.Query<int>("select count(*) from sysdatabases where [Name] = @database", new { database }).SingleOrDefault();
}

return count > 0;
}

public void Rebuild(string connectionString)
{
var builder = new SqlConnectionStringBuilder(connectionString);
Expand Down
10 changes: 10 additions & 0 deletions README.md
Expand Up @@ -24,6 +24,16 @@ or
var db = new Database(typeof(MyType).Assembly, "MyAssembly.Weird.Namespace.Folder1"); //specify what namespace the embedded create & clear sql scripts are in
```

### Check if Database Exists

To check if a database exists:

```cs
bool exists = db.Exists("server=.\\sqlexpress;database=mydb;integrated security=true;");
```

It will return `true` or `false` depending on if the database in the connection string exists or not.

### Build a Database

To build a new database using the `create.sql` script:
Expand Down

0 comments on commit b6f3fdd

Please sign in to comment.