I'm trying to create a program that can set up its own database without any need for external setup scripts. I found this question on programmatically creating a SQL Server database, but it implicitly assumes you already have a server to connect to.
If I don't, how do I create it programmatically?
const SERVER_NAME = "MyDbServer";
private DbConnection GetConnection() {
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
return new SqlConnection(connectionString);
}
public void Test(){
try {
//assume this is valid and calls GetConnection() internally
var _ = Query<int>('select count(*) from USERS', null);
} catch (System.Data.SqlClient.SqlException) {
DO SOMETHING HERE TO CREATE THE SERVER
var conn = GetConnection();
var command = SqlCommand('create database MyDatabase;', conn);
conn.Open();
command.ExecuteNonQuery();
}
What do I need to put in the "DO SOMETHING HERE TO CREATE THE SERVER" section?
EDIT: As noted in the title, this is a local server I'm trying to create. For the purposes of this question, assume that SQL Server's SqlLocalDB
is installed on this computer, but no local server exists with the name I want to use.