C# – Code to create & connect to a SQL Server database: Whats wrong with it

asp.netc++sql-server

I am new to C# & I am trying to programatically create & open a SQL Server database.

I have a ASP.NET webapp I am creating & on page load it should pull some data from the database (if the db doesn't exist, it should be created & populated with default data).

PS: does C#'s System.Data.SqlClient use MySQL or SQLite or something else?

Right now I am unsure if my code correctly creates a SQL Server database & if I connect to it correctly.

Can you tell me if my code is correct & how I could improve it?

UPDATE: Error is

"A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 – Could not open a connection to SQL
Server)"}"

I have indicated where in the code below the error occurs.

Creating a SQL Server database:

    // When I run this function no file seems to be created in my project directory?
    // Although there is a ASPNETDB sql database file in my App_Data folder so this maybe it
    public static string DEF_DB_NAME = "mydb.db"; // is this the correct extension?
    private bool populateDbDefData()
    {
        bool res = false;
        SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
        string str = "CREATE DATABASE "+DEF_DB_NAME+" ON PRIMARY " +
            "(NAME = " + DEF_DB_NAME + "_Data, " +
            "FILENAME = " + DEF_DB_NAME + ".mdf', " +
            "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
            "LOG ON (NAME = " + DEF_DB_NAME + "_Log, " +
            "FILENAME = " + DEF_DB_NAME + "Log.ldf', " +
            "SIZE = 1MB, " +
            "MAXSIZE = 5MB, " +
            "FILEGROWTH = 10%)";


        SqlCommand myCommand = new SqlCommand(str, myConn);
        try
        {
            myConn.Open(); // ERROR OCCURS HERE
            myCommand.ExecuteNonQuery();
            insertDefData(myConn);
        }
        catch (System.Exception ex)
        {
            res = false;
        }
        finally
        {
            if (myConn.State == ConnectionState.Open)
                 myConn.Close();
            res = true;
        }

        return res;
    }

Here's my connection to the SQL Server database code: I am pretty sure it fails to connect – if I try to use the variable conn, it says the connection is not open. Which could mean that I either failed to connect or failed to even create the db in the 1st place:

    private bool connect()
    {
        bool res = false;
        try
        {
            conn = new SqlConnection("user id=username;" +
                                     "password=password;" +
                                     "Server=localhost;" +
                                     "Trusted_Connection=yes;" +
                                     "database="+DEF_DB_NAME+"; " +
                                     "connection timeout=30");
            conn.Open();
            return true;
        }
        catch (Exception e)
        {
        }

        return false;
    }

Best Solution

You have probably already got this figured out, but just in case people end up here with the same problem (like I did) here's how I got this working.

Your error is that the SqlConnection is not being opened, because it isn't finding an appropriate server. If you're using the SQL server express edition (as I am) you should set the SqlConnection object like this:

SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=master;");

Once you resolve that error though, you are going to fail on the next line when you try to execute the query. The "Filename" needs to be separated by single quotes, but you only have one on the end after the extension; you will also need one before.

Also, that is the full physical file path, and it won't use the current directory context, you have to specify a path. Make sure that the location is one which the db server will have access to when it's running, otherwise you will get a SqlException being thrown with an error message along the lines of:

Directory lookup for the file "...\filename.mdf" failed with the operating system error 5 (Access is denied). CREATE DATABASE failed. Some file names listed could not be created.

The code which I ended up using looks like this:

public static string DB_NAME = "mydb"; //you don't need an extension here, this is the db name not a filename
public static string DB_PATH = "C:\\data\\";

public bool CreateDatabase()
{
    bool stat=true;
    string sqlCreateDBQuery;
    SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=master;");

    sqlCreateDBQuery = " CREATE DATABASE "
                        + DB_NAME
                        + " ON PRIMARY "
                        + " (NAME = " + DB_NAME + "_Data, "
                        + " FILENAME = '" + DB_PATH + DB_NAME + ".mdf', "
                        + " SIZE = 2MB,"
                        + " FILEGROWTH = 10%) "
                        + " LOG ON (NAME =" + DB_NAME + "_Log, "
                        + " FILENAME = '" + DB_PATH + DB_NAME + "Log.ldf', "
                        + " SIZE = 1MB, "
                        + " FILEGROWTH = 10%) ";

    SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, myConn);
    try
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
    }
    catch (System.Exception)
    {
        stat=false;
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
        myConn.Dispose();
    }
    return stat;
}