I have a C# code that works with a database to save and manage data for a library, but when I try to connect, I get this error:
Previously, I was working with the following code to declare the connection to the database, which was also throwing an exception due to an obsolete .toString() that I fixed. The code now looks like this:
public AccesoBD()
{
try
{
servidor = ConfigurationManager.AppSettings["192.168.60.54"];
bdNombre = ConfigurationManager.AppSettings["libreriawindowsform"];
usuario = ConfigurationManager.AppSettings["antonio"];
contrasena = ConfigurationManager.AppSettings[""];
}
catch (Exception e)
{
throw;
}
}
protected void abrirConexion()
{
try
{
conexion = new MySqlConnection();
conexion.ConnectionString = "Server=" + servidor + "; Database=" + bdNombre + "; Uid=" + usuario + "; Pwd=" + contrasena + ";SslMode=none;";
conexion.Open();
}
catch (Exception e)
{
throw;
}
}
I would like to know how I can make the connection work properly. I have tried connecting via the terminal with my private IP and my username (which has no password), and the connection has been successful, so the problem likely comes from the C# side.
Also, the NuGet packages seem to be correct. I have attached a screenshot of the ones I have installed.
I've been following the following instructions to try to solve it, but none of them seem to fix the problem:
The issue is likely caused by how you're retrieving values from ConfigurationManager.AppSettings
. You're using:
servidor = ConfigurationManager.AppSettings["192.168.60.54"];
bdNombre = ConfigurationManager.AppSettings["libreriawindowsform"];
usuario = ConfigurationManager.AppSettings["antonio"];
contrasena = ConfigurationManager.AppSettings[""];
This means you're trying to get settings using the actual values instead of meaningful keys. Instead, define them properly in app.config
or web.config
:
<appSettings>
<add key="Server" value="192.168.60.54"/>
<add key="Database" value="libreriawindowsform"/>
<add key="User" value="antonio"/>
<add key="Password" value=""/>
</appSettings>
Then update your C# code like this:
servidor = ConfigurationManager.AppSettings["Server"];
bdNombre = ConfigurationManager.AppSettings["Database"];
usuario = ConfigurationManager.AppSettings["User"];
contrasena = ConfigurationManager.AppSettings["Password"];
Additionally, test with a hardcoded connection string to confirm it works:
conexion.ConnectionString = "Server=192.168.60.54; Database=libreriawindowsform; Uid=antonio; Pwd=; SslMode=none;";
conexion.Open();
If the hardcoded version works but the one using AppSettings
does not, then the issue is in your config file.