Working with cloud databases is a common task in modern .NET development, and Microsoft Azure SQL Database is among the popular options, with its scalable, secure, and high-performance relational databases, ideal for both small projects and enterprise applications.
This step-by-step guide will describe how to connect your .NET application to an Azure SQL Database using Devart dotConnect for SQL Server and perform the basic operations with data.
Connect to Azure SQL Database with Data Explorer
To connect to SQL Server using the built-in Data Explorer, click Tools and select Connect to Database. Then choose SQL Server as the data source.
Enter the necessary credentials and click Connect.
Once connected, you can browse tables, execute queries, and manage data directly within the Data Explorer.
Connect and retrieve data from the database
Now that the project is ready, we can connect to Azure SQL Database to access and manipulate data.
Create DatabaseConnection.cs (connection strings)
This class keeps connection details separate for better maintainability.
using System;
using Devart.Data.SqlServer;
public static class DatabaseConnection
{
public static SqlConnection CreateOpen()
{
var connectionString = Environment.GetEnvironmentVariable("AZURE_SQL_CONN_STR") ??
"" +
"User Id=TestUser;" +
"Password=TestPassword;" +
"Data Source=test.database.windows.net;" +
"Initial Catalog=TestDatabase;" +
"License key=**********";
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
}
Connection strings
| Property |
Meaning |
| Database |
Default database to be used after connecting |
| Server or Host |
Hostname or IP address of the SQL Server |
| License Key |
Your license key. This is required only when using .NET Standard compatible assemblies |
| Password |
Password for the user ID |
| Port |
Port number on which the SQL Server is listening |
| UserId |
User ID used to authenticate with SQL Server |
Update the connection string
Replace the placeholders in the connection string with your actual SQL Server database credentials.
Note
If you own a paid license of dotConnect for SQL Server, include the license key in the connection strings.
Add the code below to the Program.cs file.
try
{
using var connection = DatabaseConnection.CreateOpen();
Console.WriteLine($"Connection State: {connection.State}\n");
const string sql = "SELECT * FROM Actor";
using var cmd = new SqlCommand(sql, connection);
using var reader = (SqlDataReader)cmd.ExecuteReader();
if (!reader.HasRows)
{
Console.WriteLine("No rows found.");
}
else
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.Write(i == 0 ? reader.GetName(i) : $", {reader.GetName(i)}");
}
Console.WriteLine();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
var value = reader.IsDBNull(i) ? "NULL" : reader.GetValue(i);
Console.Write(i == 0 ? value : $", {value}");
}
Console.WriteLine();
}
}
}
catch (SqlException ex)
{
Console.WriteLine($"SQL error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
Run the application
Build and run your application: select Start from the menu or click F5. It displays the data retrieved from the database.
Insert new records into a table in Azure SQL Database
Let's add a new record to the database. In our test case, we want to insert a new row into the Actor table using standard ADO.NET classes in the application.
try
{
using var connection = DatabaseConnection.CreateOpen();
Console.WriteLine($"Connection State: {connection.State}\n");
const string insertSql =
"INSERT INTO Actor (FirstName, LastName)\n" +
"OUTPUT INSERTED.*\n" +
"VALUES (@FirstName, @LastName);";
using (var insertCmd = new SqlCommand(insertSql, connection))
{
var pFirst = new SqlParameter("@FirstName", SqlType.VarChar, 100)
{
Direction = ParameterDirection.Input,
Value = "Michael"
};
insertCmd.Parameters.Add(pFirst);
var pLast = new SqlParameter("@@LastName", SqlType.VarChar, 100)
{
Direction = ParameterDirection.Input,
Value = "Anderson"
};
insertCmd.Parameters.Add(pLast);
using var insertedReader = (SqlDataReader)insertCmd.ExecuteReader();
Console.WriteLine("Newly inserted row:");
if (insertedReader.HasRows)
{
for (int i = 0; i < insertedReader.FieldCount; i++)
{
Console.Write(i == 0 ? insertedReader.GetName(i) : $", {insertedReader.GetName(i)}");
}
Console.WriteLine();
while (insertedReader.Read())
{
for (int i = 0; i < insertedReader.FieldCount; i++)
{
var value = insertedReader.IsDBNull(i) ? "NULL" : insertedReader.GetValue(i);
Console.Write(i == 0 ? value : $", {value}");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("Insert did not return a row.");
}
}
}
catch (SqlException ex)
{
Console.WriteLine($"SQL error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
View the results:
Update rows in Azure SQL Database
Now let's update an existing record: we can do it directly from the application. We want to modify the first and last name of an actor.
try
{
using var connection = DatabaseConnection.CreateOpen();
Console.WriteLine($"Connection State: {connection.State}\n");
const string updateSql =
"UPDATE Actor\n" +
"SET FirstName = @FirstName, LastName = @LastName\n" +
"OUTPUT INSERTED.*\n" +
"WHERE ActorID = @ActorID;";
using (var updateCmd = new SqlCommand(updateSql, connection))
{
var pId = new SqlParameter("@ActorID", SqlType.Int)
{
Direction = ParameterDirection.Input,
Value = 12
};
updateCmd.Parameters.Add(pId);
var pFirst = new SqlParameter("@FirstName", SqlType.VarChar, 100)
{
Direction = ParameterDirection.Input,
Value = "Ethan"
};
updateCmd.Parameters.Add(pFirst);
var pLast = new SqlParameter("@LastName", SqlType.VarChar, 100)
{
Direction = ParameterDirection.Input,
Value = "Whitmore"
};
updateCmd.Parameters.Add(pLast);
using var updatedReader = (SqlDataReader)updateCmd.ExecuteReader();
Console.WriteLine("Updated row:");
if (updatedReader.HasRows)
{
for (int i = 0; i < updatedReader.FieldCount; i++)
{
Console.Write(i == 0 ? updatedReader.GetName(i) : $", {updatedReader.GetName(i)}");
}
Console.WriteLine();
while (updatedReader.Read())
{
for (int i = 0; i < updatedReader.FieldCount; i++)
{
var value = updatedReader.IsDBNull(i) ? "NULL" : updatedReader.GetValue(i);
Console.Write(i == 0 ? value : $", {value}");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("No row was updated.");
}
}
}
catch (SqlException ex)
{
Console.WriteLine($"SQL error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
The application shows us updated data:
Delete rows from Azure SQL Database
To wrap up the data operations, let us remove the record we previously added. Use the below code:
try
{
using var connection = DatabaseConnection.CreateOpen();
Console.WriteLine($"Connection State: {connection.State}\n");
const string deleteSql =
"DELETE FROM Actor\n" +
"OUTPUT DELETED.*\n" +
"WHERE ActorID = @ActorID;";
using (var deleteCmd = new SqlCommand(deleteSql, connection))
{
var pId = new SqlParameter("@ActorID", SqlType.Int)
{
Direction = ParameterDirection.Input,
Value = 12
};
deleteCmd.Parameters.Add(pId);
using var deletedReader = (SqlDataReader)deleteCmd.ExecuteReader();
Console.WriteLine("Deleted row:");
if (deletedReader.HasRows)
{
for (int i = 0; i < deletedReader.FieldCount; i++)
{
Console.Write(i == 0 ? deletedReader.GetName(i) : $", {deletedReader.GetName(i)}");
}
Console.WriteLine();
while (deletedReader.Read())
{
for (int i = 0; i < deletedReader.FieldCount; i++)
{
var value = deletedReader.IsDBNull(i) ? "NULL" : deletedReader.GetValue(i);
Console.Write(i == 0 ? value : $", {value}");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("No row was deleted.");
}
}
}
catch (SqlException ex)
{
Console.WriteLine($"SQL error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
The operation is successful.
Conclusion
Connecting a .NET application to Azure SQL Database and performing basic data operations are foundational tasks for any application that deals with data stored in this relational database.
As you continue building applications with .NET, you can expand on this and proceed to more complex challenges, such as handling exceptions, working with stored procedures, or integrating data access into larger application architectures to develop more complex, data-driven applications.
FAQ
How do you install and activate dotConnect for SQL Server in a .NET project?
Install dotConnect for SQL Server via the
EXE installer or by adding the
Devart.Data.SqlServer NuGet package to your project, then obtain your personal activation key from your
Devart Customer Portal and include it in the connection string via the
License Key parameter for a working connection.
How do you create a connection to SQL Server using dotConnect in C#?
Define a connection string that includes host, user ID, password, database, and the License Key value, then create an SqlConnection instance with this string and call Open() for it inside a try-catch block to test and handle connection errors.
How do you enable encryption for secure SQL Server connections with dotConnect?
Use SQL Server Native Network Encryption by configuring encryption in the sqlnet.ora file on both client and server sides. No special parameters are required in the connection string.
Is it possible to connect to SQL Server using Visual Studio Server Explorer with dotConnect?
Yes, add a new Data Connection in Server Explorer, select dotConnect for SQL Server as the provider, enter your credentials, test the connection, and browse SQL Server data directly in Visual Studio.