Csharp/C Sharp/Database ADO.net/Create Database — различия между версиями

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

Текущая версия на 11:42, 26 мая 2010

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