I don't understand why my code doesn't execute the SqlCommand
properly, even when I don't get any errors.
Here is my code:
_connection.Connection.OpenAsync();
_connection.SqlCommand.Connection = _connection.Connection;
_connection.SqlCommand.CommandText = "insert into test (id, name) values ('dq1we3','d2qwe3')";
_connection.SqlCommand.ExecuteNonQueryAsync();
_connection.Dispose();
And here I initialize SqlConnection
and SqlCommand
:
private readonly string _conString = Settings.Default.RssConnectionString;
public SqlConnection Connection;
public SqlCommand SqlCommand;
public TestConnection()
{
Connection = new SqlConnection(_conString);
SqlCommand = new SqlCommand();
}
public void Dispose()
{
Connection.Close();
}
Should be doing something like this:
using (var myConnection = new SqlConnection(connectionString)) // using automatically disposes of object
{
myConnection.Open();
string commandText = "insert into test (id, name) values ('dq1we3','d2qwe3')";
using (var myCommand = new SqlCommand(commandText, myConnection))
{
myCommand.CommandType = CommandType.Text;
myCommand.ExecuteNonQuery();
}
}