CONTEXT: I am writing a WPF app. It works with a SQL Server database in which I put some data, concretely the strings Titulo and Descripcion, the int XP and the string fotoMision. When I click a button the program is supposed to save this data in the database.
PROBLEM: when I click the button it throws me an exception in string connection’s line showing that the object is not instanced. If I put these first lines right below the InitializeComponent();
line the second one doesn’t recognise the miConexion
string. Why does that happen and how can I fix it?
CODE:
static string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString; SqlConnection miConexionSql = new SqlConnection(miConexion); private void Button_Click(object sender, EventArgs e) { string consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision"; SqlCommand miSqlCommand = new SqlCommand(consulta, miConexionSql); miConexionSql.Open(); miSqlCommand.Parameters.AddWithValue("@Titulo", tituloMision); miSqlCommand.ExecuteNonQuery(); miConexionSql.Close(); }
Advertisement
Answer
Connections are meant to be short-lived, i.e. you should create one when the button is clicked and then dispose it right after you have executed the query. Using a using
statement implicitly disposes the IDisposable
:
private void Button_Click(object sender, EventArgs e) { const string Consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision"; string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString; using (SqlConnection miConexionSql = new SqlConnection(miConexion)) using (SqlCommand miSqlCommand = new SqlCommand(Consulta, miConexionSql)) { miConexionSql.Open(); miSqlCommand.Parameters.AddWithValue("@Titulo", tituloMision); miSqlCommand.ExecuteNonQuery(); miConexionSql.Close(); } }