Csharp/C Sharp/Database ADO.net/Create Database

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Create database through SqlConnection

using System;
using System.Data;
using System.Data.SqlClient;
   class CommandExampleCreateDb
   {
      static void Main() 
      {
         SqlConnection thisConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
         SqlCommand nonqueryCommand = thisConnection.CreateCommand();
         try 
         {
            thisConnection.Open();
            nonqueryCommand.rumandText = "CREATE DATABASE MyDb";
            Console.WriteLine(nonqueryCommand.rumandText);
            nonqueryCommand.ExecuteNonQuery();
            Console.WriteLine("Database created, now switching");
            thisConnection.ChangeDatabase("MyDb");
            nonqueryCommand.rumandText = "CREATE TABLE MynfexTable (COL1 integer)";
            Console.WriteLine(nonqueryCommand.rumandText);
            Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());
            nonqueryCommand.rumandText = "INSERT INTO MynfexTable VALUES (99)";
            Console.WriteLine(nonqueryCommand.rumandText);
            Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());
         
         } catch (SqlException ex) {
         
            Console.WriteLine(ex.ToString());
         
         } finally {  
         
            thisConnection.Close();
            Console.WriteLine("Connection Closed.");
         
         }
      }
   }