I
I
Ingvar Von Bjork2017-04-09 12:17:04
SQL
Ingvar Von Bjork, 2017-04-09 12:17:04

How to fix "No connection associated with this command" error?

SQLiteConnection connect = new SQLiteConnection("Data Source=base.db;");
connect.Open();
SQLiteCommand command = new SQLiteCommand(@"UPDATE voices SET pass = '" + pass + 
      "', hash = '" + hash + 
      "' WHERE id = '" + id + "'");
command.ExecuteNonQuery();
connect.Close();

The record in the table is not actually updated - it ends with the error "No connection associated with this command" on the 6th line.
What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-stream, 2017-04-09
@DeboshiR

Well, that's logical. Connection in itself, command - in itself.
If you just look at the description of SqlCommand (architecture for SQLite is the same) https://msdn.microsoft.com/en-us/library/system.da...
then you can see the following:

using (SqlConnection conn = new SqlConnection(connectionString)) {
            using (SqlCommand cmd = new SqlCommand(commandText, conn)) {
               // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect 
               // type is only for OLE DB.  
               cmd.CommandType = commandType;
               cmd.Parameters.AddRange(parameters);

               conn.Open();
               return cmd.ExecuteNonQuery();
            }
         }

The command is constructed with reference to the connection that it will use.
Exactly the same example is given in the description of SQLiteCommand
https://www.devart.com/dotconnect/SQLite/docs/Deva...
public void ReadMyData(string myConnString)
{
  string mySelectQuery = "SELECT DeptNo, DName FROM Dept";
  SQLiteConnection sqConnection = new SQLiteConnection(myConnString);
  SQLiteCommand sqCommand = new SQLiteCommand(mySelectQuery,sqConnection); // команда конструируется с указанием соединения!!!
  sqConnection.Open();
  SQLiteDataReader sqReader = sqCommand.ExecuteReader();
  try
  {
    while (sqReader.Read())
    {
      Console.WriteLine(sqReader.GetInt32(0).ToString() + ", " + sqReader.GetString(1));
    }
  }
  finally
  {
  // always call Close when done reading.
  sqReader.Close();
  // always call Close when done reading.
  sqConnection.Close();
  }
}

In general, the answer to the question "how to fix" is one - to understand the essence.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question