我正在学习 C# 和 SQL 数据库,但主要是 C#。我正在从事一个项目,我们需要将一些数据写入 SQL Server 数据库。
这是我的连接字符串:
<configuration>
<connectionStrings>
<add name="conexionServidorHotel"
connectionString="Data Source=DESKTOP-QG08OQQ\\SQLEXPRESS;Initial Catalog=Script_RESORTSUNED;Integrated Security=True;"/>
</connectionStrings>
</configuration>
这是我当前使用的代码:
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;
}
}
}
我的项目是西班牙语的。这就是变量名称采用西班牙语的原因。当我运行代码并输入 Hotel 对象的数据时,工作正常,直到
conexion.Open()
。
有些东西告诉我该命令有问题,但不确定是什么。向我抛出问题标题中的信息。
我检查了连接字符串,它对我来说看起来不错。我的 SQL Server 文件与 C# 解决方案不在同一目录中,而是在前一个目录中。我不确定使用
Microsoft.Data.SqlClient
是否也会产生影响。
如果在
Open()
处失败,有两种选择:
cadenaConexion
无效(我们看不到);重新检查一下,或者尝试使用 SqlConnectionStringBuilder
;重新检查服务器、数据库、身份验证、证书(如果需要)等