ADO .Net – Create Table in SQL Server

Create table in SQL server:

  • We create SQLCommand object by passing sql statement as an input.
  • SQLCommand constructor taking connection object and sql statement as inputs.
  • We invoke ExecuteNonQuery() method to run the sql statement.
using System;
using System.Data.SqlClient;
namespace Practice
{
            class Program
            {
                        static void Main(string[] args)
                        {
                                    SqlConnection con = null;
                                    try
                                    {
                                                con = new SqlConnection(“data source=.; database=fullstack; integrated security=SSPI”);
                                                con.Open();
                                                Console.WriteLine(“Connected”);
 
                                                String query = “create table account(num int, name varchar(20), balance int)”;
                                                SqlCommand cm = new SqlCommand(query, con);
                                                cm.ExecuteNonQuery();
                                                Console.WriteLine(“Table created Successfully”);
                                    }
                                    catch (Exception e)
                                    {
                                                Console.WriteLine(“OOPs, something went wrong.” + e);
                                    }
                                    finally
                                    {
                                                con.Close();
                                                Console.WriteLine(“Connection closed”);
                                    }
                        }
            }
}
Scroll to Top