Creating Databases and tables using c#

2019-04-17 07:31发布

问题:

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.

回答1:

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();


回答2:

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");



回答3:

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();