0

I have a windows form application created using C#. I have a few databases and tables in SQL server 2005 express edition. To create a setup of my project I wish to attach the databases and tables dynamically while my setup wizard runs on any remote machine.

I tried to write a code which will simply create database and also a try-catch statement which will check if the database exists but everytime execution of try catch statement whenever my application runs may be a problem.

Is this possible by simply attaching the .mdf files with my project as I create the setup wizard ?

Please help. Thanks in advance.

4
  • Use simple ADO.net to create databases. Commented Mar 29, 2013 at 10:40
  • @HosseinNarimaniRad: Sir is it possible to do it using SQL server ? i mean a ADO.net connection with SQL server ? how can it be done ? Commented Mar 29, 2013 at 10:41
  • I post an answer. Please see my answer. Commented Mar 29, 2013 at 10:51
  • 1
    @HosseinNarimaniRad: The answer is useful sir but my question is how can we write a connection string as the database is also to be created dynamically. Commented Mar 29, 2013 at 11:57

3 Answers 3

2

To create a table:

string createString = "CREATE TABLE myTable (column1 INT, column2 NVARCHAR(10))"; //YOUR SQL COMMAND TO CREATE A TABLE
SqlConnection connection = new SqlConnection(YOUR CONNECTION STRING);

SqlCommand create = new SqlCommand(createString , connection);

connection.Open();
create.ExecuteNonQuery();
connection.Close();
Sign up to request clarification or add additional context in comments.

Comments

0

You could copy your .mdf file in root and if you make a setup it would be in your setup file. I had done it. Your connection string would be: string.Format("{0}{1}{2}", @"Data Source=.\SQLEXPRESS;AttachDbFilename=", AppDomain.CurrentDomain.BaseDirectory, @"Database.mdf;Integrated Security=True;User Instance=False");

Comments

0
string myConnectionString= @"DataSource =...";

SqlConnection dbConnection = new SqlConnection(myConnectionString);

string myCommand = "CREATE TABLE myTable (column1 VARCHAR(10),colunm2 INT)";

SqlCommand dbConnection = new SqlCommand(myCommand,dbConnection);

try
{
dbConnection.Open();

dbCommand.ExecuteNonQuery();
}

catch{}

dbConnection.Close();

Comments

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.