Konrad Viltersten
Konrad Viltersten

Reputation: 39058

How to actually execute a command?

I'm playing around making a POC and I've created the following call.

public string DoStuff()
{
  try
  {
    using (SqlDataAdapter adapter = new SqlDataAdapter())
    {
      SqlConnection connection = new SqlConnection("Server...");
      string command = "insert into Records values (...)";
      adapter.InsertCommand = new SqlCommand(command, connection);
    }
  }
  catch (Exception exception)
  {
    return exception.Message + " " + exception.InnerException;
  }
  return "WeeHee!";
}

The text I'm seeing returned is the happy one, so I conclude there's no exceptions. Hence, I conclude that the call to the DB is performed as supposed to. However, there's no new lines in the DB being created.

I'm using the same connection string as I have in my config file and the command in pasted in from SQL Manager, where it works.

So my suspicion was that although I create an insert command, I never actually execute it but according to MSDN that's how it's supposed to work.

What stupid thing do I miss here?

Upvotes: 1

Views: 77

Answers (4)

weston
weston

Reputation: 54781

The example you linked to returned a SQLAdapter for later use.

You don't need one at all:

 using (SqlConnection connection = new SqlConnection("Server..."))
 {
     string command = "insert into Records values (...)";
     connection.Open();
     var command = new SqlCommand(command, connection);
     command.ExecuteNonQuery();
 }

Note that there are other execution methods, depending on expected return values and whether you want asynchronous operation: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98740

You should use ExecuteNonQuery instead. Using an SqlDataAdapter for an INSERT query does not make sense.

Also you should Open your connection just before you execute it.

Upvotes: 2

mehmet mecek
mehmet mecek

Reputation: 2685

You can:

using(SqlConnection connection = new SqlConnection("Server..."))
{
  SqlCommand command = connection.CreateCommand();
  command.CommandText = "insert into Records values (...)";
  connection.Open();
  int craeted = command.ExecuteNonQuery();
}

Upvotes: 1

Valentin
Valentin

Reputation: 5488

You are missing connection.Open(); and adapter.InsertCommand.ExecuteNonQuery();

using (SqlDataAdapter adapter = new SqlDataAdapter())
{
  SqlConnection connection = new SqlConnection("Server...");
  connection.Open();
  string command = "insert into Records values (...)";
  adapter.InsertCommand = new SqlCommand(command, connection);
  adapter.InsertCommand.ExecuteNonQuery(); 
}

Upvotes: 2

Related Questions