Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create database if it doesn't exists with Dapper

Can I check if the database exists when creating the connection and if such a database does not exist, then run the script to create the database? I use Dapper. This is how I create a connection:

private static IDbConnection GetConnection(IConfigHelper config)
        {
            var factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

            var connection = factory.CreateConnection();
            connection.ConnectionString = config.ConnectionString;
            connection.Open();

            return connection;
        }

Different environments may be used in the future, so I need this check.

like image 436
Michael Kostiuchenko Avatar asked Aug 05 '26 19:08

Michael Kostiuchenko


1 Answers

Include this in your db-creation-script and simply allways run it upon initializing your connection.

IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = 'yourDB')
  BEGIN
    CREATE DATABASE yourDB
  END
like image 196
Sancho Panza Avatar answered Aug 08 '26 10:08

Sancho Panza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!