Reputation: 1
I'm working in a project in which we need to write down some data into a SQL Server database.
This is my connection string:
<configuration>
<connectionStrings>
<add name="conexionServidorHotel"
connectionString="Data Source=DESKTOP-QG08OQQ\\SQLEXPRESS;Initial Catalog=Script_RESORTSUNED;Integrated Security=True;"/>
</connectionStrings>
</configuration>
And this is the code I'm currently using:
using Entidades;
using System.Configuration;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
namespace AccesoDatos
{
public class HotelAD
{
private string cadenaConexion;
public HotelAD()
{
cadenaConexion = ConfigurationManager.ConnectionStrings["conexionServidorHotel"].ConnectionString;
}
public bool RegistrarHotel(Hotel NuevoHotel)
{
bool hotelregistrado = false;
try
{
SqlConnection conexion;
SqlCommand comando = new SqlCommand();
using (conexion = new SqlConnection(cadenaConexion))
{
string instruccion = " Insert Into Hotel (IdHotel, Nombre, Direccion, Estado, Telefono)" +
" Values (@IdHotel, @Nombre, @Direccion, @Estado, @Telefono)";
comando.CommandType = CommandType.Text;
comando.CommandText = instruccion;
comando.Connection = conexion;
comando.Parameters.AddWithValue("@IdHotel", NuevoHotel.IDHotel);
comando.Parameters.AddWithValue("@Nombre", NuevoHotel.NombreHotel);
comando.Parameters.AddWithValue("@Direccion", NuevoHotel.DireccionHotel);
comando.Parameters.AddWithValue("@Estado", NuevoHotel.StatusHotel);
comando.Parameters.AddWithValue("@Telefono", NuevoHotel.TelefonoHotel);
conexion.Open();
Debug.WriteLine("Aqui voy bien 7");
hotelregistrado = comando.ExecuteNonQuery() > 0;
}
}
catch (InvalidOperationException)
{
Debug.WriteLine("No puedo escribir en la base de datos");
}
return hotelregistrado;
}
}
}
My project is in Spanish. That is why variable names are in Spanish. When I run my code, and I input the data for the Hotel object, it works fine until conexion.Open()
.
Something tells me there's something wrong with that command but not sure what. Its throwing me the error:
'System.InvalidOperationException' in Microsoft.Data.SqlClient.dll
I reviewed the connection string and it looks good to me. The SQL Server file I have is not in the same directory as the C# solution but one directory before. I'm not sure if using Microsoft.Data.SqlClient
could be affecting too.
Upvotes: 0
Views: 375
Reputation: 1062492
If it fails at Open()
, there are two options:
cadenaConexion
is invalid (which we can't see); recheck it, or try using SqlConnectionStringBuilder
; recheck the server, database, auth, certs if needed, etcUpvotes: 0