2
I’m starting now with C# and I’m having some problems at the time of developing this code, I was aiming to create a DAO with a simple connection and then instance it and then insert it into the bank. but it makes an error that the connection should be opened, but I open it there at DAO, so it helps that I’m confused on this
OBS1: I’ve made the changes that I understood in what the colleague Olivier suggested, but I’m still a little lost
OBS2: I managed to resolve the issue, I’ll leave the code in case someone is starting to study the 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();
}
}
}
}
Thanks in advance!
Post the answer as the answer, don’t mix the question with the answer. It’s okay to answer the question itself. What gets bad is the confusion between the two posts.
– Maniero