Descargar e Instalar:
Microsoft.Data.SqlClient
System.Configuration.ConfigurationManager
En el App.config del proyecto principal:
Configuramos la cadena de conexión para SQL SERVER
<connectionStrings>
<add name="SqlCn" connectionString="Data Source=TI\MSSQLSERVER2022;Initial Catalog=salesdb;Integrated Security=True" />
<add name="SqlCn" connectionString="Data Source=TI\MSSQLSERVER2022;Initial Catalog=salesdb;Integrated Security=True" />
</connectionStrings>
ó
<connectionStrings> <add name="SqlServerCn" connectionString="Server=TI;Database=testdb;uid=sa;pwd=123456";Encrypt=False />
</connectionStrings>
Otra Forma:
string cadena = @"server = TI\MSSQLSERVER;database = Negocios2022;Trusted_Connection = True;MultipleActiveResultSets = True;TrustServerCertificate = False;Encrypt = False";
En el código C#
Creamos la clase Connection o Database
------------------------------------------------------------------------------
public class Connection
{
private static Connection instance;
private Connection() { }
public static Connection GetInstance()
{
if (instance == null)
{
instance = new Connection();
}
return instance;
}
public SqlConnection GetConnection()
{
string connectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
return new SqlConnection(connectionString);
}
}
---------------------------------------------------------------------------------------------------------------
public class Connection
{
private static Connection instance;
private static readonly object _lock = new object();
private Connection() { }
public static Connection GetInstance()
{
if (instance == null)
{
lock (_lock)
{
if(instance == null)
{
instance = new Connection();
}
}
}
return instance;
}
public SqlConnection GetConnection()
{
string connectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
return new SqlConnection(connectionString);
}
}
-----------------------------------------------------------------------------------------------------------------
Validar la conexion a la base de datos en C# Windows Form
private void btnConnection_Click(object sender, EventArgs e)
{
try
{
Database database = new Database();
using (SqlConnection conn = database.GetConnection())
{
conn.Open();
MessageBox.Show("Conexión exitosa");
}
}
catch (Exception ex)
{
MessageBox.Show("Conexión fallida: " + ex.Message);
}
}