Primeros Pasos en SQL Server
Primeros Pasos en SQL Server
Visual Studio creates a new C# Console Application project and opens the file Program.cs.
Replace the contents of Program.cs by copying and pasting the code below into the file.
Don’t forget to replace the username and password with your own. Save and close the file.
using System;
using System.Text;
using System.Data.SqlClient;
namespace SqlServerSample
{
class Program
{
static void Main(string[] args)
{
try
{
// Build connection string
SqlConnectionStringBuilder builder = new
SqlConnectionStringBuilder();
builder.DataSource = "localhost"; // update me
builder.UserID = "sa"; // update me
builder.Password = "your_password"; // update me
builder.InitialCatalog = "master";
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new
SqlConnection(builder.ConnectionString))
{
connection.Open();
Console.WriteLine("Done.");
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Now replace the code in Program.cs by copying and pasting the code below into the file. This will
create a database and a table, and will insert, update, delete, and read a few rows. Don’t forget to
update the username and password with your own. Save and close the file.
using System;
using System.Text;
using System.Data.SqlClient;
namespace SqlServerSample
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Connect to SQL Server and demo Create,
Read, Update and Delete operations.");
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new
SqlConnection(builder.ConnectionString))
{
connection.Open();
Console.WriteLine("Done.");
// INSERT demo
Console.Write("Inserting a new row into table, press
any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("INSERT Employees (Name, Location) ");
sb.Append("VALUES (@name, @location);");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql,
connection))
{
command.Parameters.AddWithValue("@name", "Jake");
command.Parameters.AddWithValue("@location",
"United States");
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s)
inserted");
}
// UPDATE demo
String userToUpdate = "Nikita";
Console.Write("Updating 'Location' for user '" +
userToUpdate + "', press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("UPDATE Employees SET Location = N'United
States' WHERE Name = @name");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql,
connection))
{
command.Parameters.AddWithValue("@name",
userToUpdate);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s)
updated");
}
// DELETE demo
String userToDelete = "Jared";
Console.Write("Deleting user '" + userToDelete + "',
press any key to continue...");
Console.ReadKey(true);
sb.Clear();
sb.Append("DELETE FROM Employees WHERE Name =
@name;");
sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql,
connection))
{
command.Parameters.AddWithValue("@name",
userToDelete);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s)
deleted");
}
// READ demo
Console.WriteLine("Reading data from table, press any
key to continue...");
Console.ReadKey(true);
sql = "SELECT Id, Name, Location FROM Employees;";
using (SqlCommand command = new SqlCommand(sql,
connection))
{
Visual Studio creates a new C# Console Application project and opens the file Program.cs.
1. Open the Package Manager Console in Visual Studio with “Tools -> Nuget Package
Manager -> Package Manager Console”
2. Type: “Install-Package EntityFramework”
3. Hit enter
Close the Package Manager Console. You have successfully added the required Entity
Framework dependencies to your project.
For this sample, let’s create two tables. The first will hold data about “users” and the other
will hold data about “tasks”.
Create User.cs:
Copy and paste the following code into the User.cs file. Save and close the file.
using System;
using System.Collections.Generic;
namespace SqlServerEFSample
{
public class User
{
public int UserId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public virtual IList<Task> Tasks { get; set; }
Copy and paste the following code into the Task.cs file. Save and close the file.
using System;
namespace SqlServerEFSample
{
public class Task
{
public int TaskId { get; set; }
public string Title { get; set; }
public DateTime DueDate { get; set; }
public bool IsComplete { get; set; }
public virtual User AssignedTo { get; set; }
Create EFSampleContext.cs:
Copy and paste the following code into the EFSampleContext.cs file. Save and close the
file.
using System;
using System.Data.Entity;
namespace SqlServerEFSample
{
public class EFSampleContext : DbContext
{
public EFSampleContext(string connectionString)
{
Database.SetInitializer<EFSampleContext>(new
DropCreateDatabaseAlways<EFSampleContext>());
this.Database.Connection.ConnectionString = connectionString;
}
public DbSet<User> Users { get; set; }
public DbSet<Task> Tasks { get; set; }
}
}
Replace the code in the Program.cs file in your by copying and pasting the code into the file. Don’t
forget to update the username and password with your own. Save and close the file.
using System;
using System.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;
namespace SqlServerEFSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("** C# CRUD sample with Entity Framework
and SQL Server **\n");
try
{
// Build connection string
SqlConnectionStringBuilder builder = new
SqlConnectionStringBuilder();
builder.DataSource = "localhost"; // update me
builder.UserID = "sa"; // update me
builder.Password = "your_password"; // update me
builder.InitialCatalog = "EFSampleDB";
Congrats you just created two C# apps! Check out the next section to learn about how you
can make your C# apps faster with SQL Server’s Columnstore feature.
Now that you have explored the basics, you are ready to see how you can make your app better
with SQL Server. In this module we will show you a simple example of Columnstore Indexes and
how they can improve data processing speeds. Columnstore Indexes can achieve up to 100x better
performance on analytical workloads and up to 10x better data compression than traditional
rowstore indexes.
Step 3.1
Note! With the introduction of Service Pack 1 for SQL Server 2016, features in the
database engine related to application development are now available across all editions of
SQL Server (from Express through Enterprise). This includes innovations that can
significantly improve your application’s throughput, latency, and security. Examples
include the in-memory columnstore used in this tutorial, in-memory OLTP, data
compression, table partitioning, Hadoop integration with PolyBase, Always Encrypted,
row-level security, and data masking. Enjoy!
Visual Studio creates a new C# Console Application project and opens the file Program.cs.
Replace the contents of Program.cs by copying and pasting the code below into the file.
Don’t forget to replace the username and password with your own. Save and close the file.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlServerColumnstoreSample
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("*** SQL Server Columnstore demo ***");
The performance of the query was greatly improved! Now that you’ve built a few C# apps with
SQL Server and .NET Core, continue checking out other SQL Server features.
Follow the steps here to install and use the mssql extension for VS Code.