SQL C#

Create an SQL Table with a Primary Key

This C# program demonstrates how to create an SQL table with a primary key for Microsoft SQL in C#.

Program.cs

using System;
using System.Data.SqlClient;

namespace CreateTable {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine(CreateTable());
        }

        public static int CreateTable() {
            // The using block ensures that the connection is closed when it exits this block.
            using (SqlConnection qConnection = new SqlConnection(
                    @"Server=localhost\SQLEXPRESS01;Database=xoax;Trusted_Connection=True;")) {
                SqlCommand qCommand = qConnection.CreateCommand();
                // The first column is the primary key.
                // It is also an int value that is automatically generated,
                // starting at 1 and incrementing by 1 for each entry.
                qCommand.CommandText = "CREATE TABLE people(id int IDENTITY(1,1) PRIMARY KEY,"
                    + " name varchar(30), state varchar(2));";
                qCommand.Connection.Open();
                return qCommand.ExecuteNonQuery();
            }
        }
    }
}
 

Output

-1
Press any key to continue . . .
 

Before

Before
 

After

After
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.