Use SQL command to insert data into database table : Insert « Database ADO.net « C# / C Sharp






Use SQL command to insert data into database table


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.CommandText = "CREATE DATABASE MyDb";
            Console.WriteLine(nonqueryCommand.CommandText);

            nonqueryCommand.ExecuteNonQuery();
            Console.WriteLine("Database created, now switching");
            thisConnection.ChangeDatabase("MyDb");

            nonqueryCommand.CommandText = "CREATE TABLE MyJava2sTable (COL1 integer)";
            Console.WriteLine(nonqueryCommand.CommandText);
            Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());

            nonqueryCommand.CommandText = "INSERT INTO MyJava2sTable VALUES (99)";
            Console.WriteLine(nonqueryCommand.CommandText);
            Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());
         
         } catch (SqlException ex) {
         
            Console.WriteLine(ex.ToString());
         
         } finally {  
         
            thisConnection.Close();
            Console.WriteLine("Connection Closed.");
         
         }
      }
   }


           
       








Related examples in the same category

1.Bind parameters to insert command
2.Run an INSERT statement with parameters
3.Inserte Data Using SQL Statements
4.Insert Data Using SqlCommandBuilder