-3

I am new to SQL and trying to create a Database using C#. Here is my Code...

private void CreateDBBtn_Click(object sender, EventArgs e)
{
  String connectionString = GetConnectionString();
  SqlConnection connection = new SqlConnection(connectionString);
  connection.Open();

  String SQLCommand = "CREATE DATABASE MyDatabase ON PRIMARY " +
           "(NAME = MyDatabase_Data, " +
           "FILENAME = 'D:\\MyDatabase.mdf'," +
           "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)";

  SqlCommand cmd = new SqlCommand(SQLCommand, connection);
  try
  {
    cmd.ExecuteNonQuery();
  }
  catch (SqlException ae)
  {
    MessageBox.Show(ae.Message);
  }
}

private String GetConnectionString()
{
   SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
   builder.DataSource = @".\SQLSERVER";
   builder.AttachDBFilename = @"D:\MyDatabase.mdf";
   builder.IntegratedSecurity = true;
   builder.ConnectTimeout = 30;
   builder.UserInstance = true;
   return builder.ConnectionString;
}

but it gives me error that...

enter image description here

Where as D:\MyDataBase.mdf file has size 3.13 MB on my PC.

5
  • 2
    Why not use the Database server to Create the Database.. Commented Jun 18, 2013 at 17:56
  • 7
    So set SIZE = 5MB then. Also MAXSIZE = 10MB? Surely you can afford more space than that? Commented Jun 18, 2013 at 17:58
  • The error says it has to be 5MB. You said it is 3.13MB. Did you try boosting the initial size? Also, did you try scripting a samlple of the database from the sql server gui and then use that in your code? I wouldn't do it the way you are doing anyhow but those are some things I would try. Commented Jun 18, 2013 at 17:59
  • Yes, @MartinSmith, SIZE = 5B worked for me but I feel the Problem was this file Name builder.AttachDBFilename = @"D:\MyDatabase.mdf"; and the One in Create DataBase "FILENAME = 'D:\\MyDatabase.mdf', should also be different. Commented Jun 18, 2013 at 18:17
  • [refer this site][1]stackoverflow.com/questions/14034351/… Commented Jun 18, 2013 at 18:31

1 Answer 1

-1

I completely agree with DJ KRAZE. It would take about two seconds to create that using whatever server manager you have.

Sign up to request clarification or add additional context in comments.

3 Comments

This is a comment, not an answer.
I have to have 50 reputation points to be able to comment. Otherwise I would have.
I agree @khinkle that it will take hardly 2 seconds to create using DataBase server but then I will never learn how to do that using C# and My First Line was "I am new to SQL and trying to create a Database using C#".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.