I'm starting now with C # and I have some problems when developing this code, I was aiming to create a DAO with a simple connection and then instantiate it and then do the insertion in the database. but it gives a mistake that the connection should be open, but I open it there in DAO, so give a help that I'm confused about it
OBS1: I made the changes where I understood what colleague Olivier suggested, but I'm still a bit lost
OBS2: I was able to resolve the issue, I will leave the code in case anyone is starting to study C #
DAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CRUD_MYSQL
{
public class Dao
{
private MySqlConnection conn = null;
public MySqlConnection conectar()
{
string connectionString = "server=localhost;uid=root;pwd=;database=dbalbuns";
this.conn = new MySqlConnection(connectionString);
this.conn.Open();
try
{
if (this.conn.State == ConnectionState.Open)
{
HttpContext.Current.Response.Write("Conectado");
}
return this.conn;
}
catch (Exception)
{
HttpContext.Current.Response.Write("erro de conexão");
return this.conn;
}
}
}
}
WebForm1.apsx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;
namespace CRUD_MYSQL
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Dao conectar = new Dao();
MySqlConnection Conexao = conectar.conectar();
string query = "insert into albuns (titulo, descricao, preco) values ('a', 'a', '1')";
using (MySqlCommand cmd = new MySqlCommand(query, Conexao))
{
cmd.ExecuteNonQuery();
}
}
}
}
Thank you in advance!