Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to create & connect to a SQL Server database: Whats wrong with it?

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;
    }
like image 444
sazr Avatar asked Dec 29 '25 11:12

sazr


2 Answers

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;
}
like image 151
nbrooks Avatar answered Jan 01 '26 02:01

nbrooks


Use this code,

internal class CommonData
  {
    private static SqlConnection conn;

    public static SqlConnection Connection
    {
        get { return conn; }
    }

    public static void ReadyConnection()
    {
        conn = new SqlConnection();
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
        if (conn.State != ConnectionState.Open)
        {
            conn.Open();
        }
    }

    public static int ExecuteNonQuery(SqlCommand command)
    {
        try
        {
            ReadyConnection();
            command.Connection = conn;
            int result = command.ExecuteNonQuery();
            return result;
        }
        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            command.Dispose();
            if (conn.State == ConnectionState.Open) conn.Close();
            conn.Dispose();
        }
    }

    public static SqlDataReader ExecuteReader(SqlCommand command)
    {
        try
        {
            ReadyConnection();
            command.Connection = conn;
            SqlDataReader result = command.ExecuteReader(CommandBehavior.CloseConnection);
            return result;
        }
        catch (Exception Ex)
        {

            throw Ex;
        }
    }

    public static object ExecuteScalar(SqlCommand command)
    {
        try
        {
            ReadyConnection();
            command.Connection = conn;

            object value = command.ExecuteScalar();
            if (value is DBNull)
            {
                return default(decimal);
            }
            else
            {
                return value;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static void ClearPool()
    {
        SqlConnection.ClearAllPools();
    }
}
like image 24
Sasika Miyuran Avatar answered Jan 01 '26 04:01

Sasika Miyuran



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!