Search code examples
c#sqlfirebird

Updating Firebird DB every timer's tick in C#


i'd like to update field in my db every tick of timer:

I know how to read from db, but i don't know how to send it to db.. My code:

private void Timer1_tick(object sender, EventArgs e)
{
    FbConnection UpdateConnection = new FbConnection(ConnectionString);
    UpdateConnection.Open();
    FbCommand readCommand = new FbCommand("UPDATE Param SET Test=" + TestTextBox.Text, UpdateConnection);
    FbDataReader myreader = readCommand.ExecuteReader();
    UpdateConnection.Close();

}

And is it a good way to update my database? I'll have lot o parameters to update every tick (second), so maybe there is another proper way of doing this?


Solution

  • An update query uses ExecuteNonQuery not ExecuteReader. No need to build a DataReader when you don't read anything.

    Also put a using statement around the connection (to be certain that the connection will be closed in case of exceptions).
    Finally, (and probably the most important advice), use always parameters to work with databases.

    private void Timer1_tick(object sender, EventArgs e) 
    { 
        using(FbConnection UpdateConnection = new FbConnection(ConnectionString))
        {
            UpdateConnection.Open(); 
            FbCommand writeCommand = new FbCommand("UPDATE Param SET Test=@myData", UpdateConnection); 
            writeCommand.Parameters.AddWithValue("@myData", TextBox1.Text);
            int recUpdated = writeCommand.ExecuteNonQuery(); 
        }
    }