ADO - SQL Server - Create Table
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=(local);Initial Catalog=YourDatabaseName;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
// Connection opened successfully
Console.WriteLine("Connected to the database.");
// Create a table
string createTableQuery = "CREATE TABLE YourTableName (Id INT PRIMARY KEY, Name NVARCHAR(50))";
SqlCommand createTableCommand = new SqlCommand(createTableQuery, connection);
createTableCommand.ExecuteNonQuery();
Console.WriteLine("Table created successfully.");
}
catch (Exception ex)
{
// Handle any errors
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
In the above code, make sure to replace "YourDatabaseName" with the actual name of the database you want to connect to and "YourTableName" with the desired name for your table.
Here's an explanation of the code:
- We start by defining the connection string, which includes the necessary details to connect to the SQL Server database. Update the "Data Source" to your server name or IP address, and "Initial Catalog" to your database name.
- Inside the using block, we create a new SqlConnection object and pass the connection string as the constructor parameter. The using statement ensures that the connection is properly closed and disposed of when we're done with it.
- We attempt to open the connection using the Open method. If the connection is successful, we print a message indicating that the connection has been established.
- We define the SQL query to create the table in the createTableQuery variable. Replace "YourTableName" with the desired name for your table, and define the columns and their data types according to your requirements.
- We create a new SqlCommand object with the createTableQuery and the connection as parameters.
- We execute the query using the ExecuteNonQuery method of the SqlCommand object. This method is used for executing queries that don't return any data.
- If the table creation is successful, we print a message indicating that the table has been created.
- If any errors occur during the process, they are caught in the catch block, and an error message is displayed.
Remember to include the necessary namespaces at the top of your C# file:
using System;
using System.Data.SqlClient;
Compile and run the code to establish a connection to your SQL Server database and create the table. Make sure you have appropriate permissions to create tables in the specified database.
Note that this example demonstrates table creation, but you can modify it to include additional columns and constraints as needed for your specific table design.