Database Usage with .NET
Connecting and interacting with databases is a common task in many applications. In .NET, you can use the System.Data.SqlClient
namespace to connect to and interact with Microsoft SQL Server databases.
To establish a connection to a SQL Server database, you need to provide a connection string that contains the necessary information such as the server name, the database name, and the authentication details. Here's an example of a connection string:
TEXT/X-CSHARP
1Server=localhost;Database=MyDatabase;User Id=myUsername;Password=myPassword;```+
2
3Once you have the connection string, you can create a `SqlConnection` object and open the connection using the `Open` method. After that, you can perform various database operations such as executing SQL queries or stored procedures.
4
5Here's an example of how you can connect to a SQL Server database using .NET:
6
7```csharp
8using System;
9using System.Data.SqlClient;
10
11public class Program
12{
13 public static void Main()
14 {
15 // Connection string for connecting to a SQL Server database
16 string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUsername;Password=myPassword;";
17
18 // Create a connection object
19 using (SqlConnection connection = new SqlConnection(connectionString))
20 {
21 try
22 {
23 // Open the connection
24 connection.Open();
25 Console.WriteLine("Connection opened successfully!");
26
27 // Use the connection to interact with the database
28 // ...
29 }
30 catch (Exception ex)
31 {
32 Console.WriteLine("Error: " + ex.Message);
33 }
34 }
35 }
36}
xxxxxxxxxx
29
using System;
using System.Data.SqlClient;
public class Program
{
public static void Main()
{
// Connection string for connecting to a SQL Server database
string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUsername;Password=myPassword;";
// Create a connection object
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
// Open the connection
connection.Open();
Console.WriteLine("Connection opened successfully!");
// Use the connection to interact with the database
// ...
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment