Victor Lev
Victor Lev

Reputation: 1

Access DB, No reaction from the DB

Encountered with a problem... maybe something in the syntax of the query, and the compiler doesn't throw any Exception. But the table do not receive information.

Anything you noticed that maybe wrong?

OleDbConnection conn;
OleDbCommand cmd;


public Commands(OleDbConnection con)
{
    conn = con;
}


public Commands()
{
    conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DB.accdb");
}

public void node_Join(int id, byte[] mac)
{
    try
    {
        conn.Open();
        cmd = new OleDbCommand(@"INSERT INTO Nodes ([J_ID],[Node ID],[Node MAC],[Line Quality],[Status]) values('" + Convert.ToString(id) + @"',0,'" + BitConverter.ToString(mac) + @"',0,'Join')", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
    }
    catch (Exception exc)
    {
        conn.Close();
        MessageBox.Show(exc.Message.ToString());
    }
}

Upvotes: 0

Views: 340

Answers (1)

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

Reputation: 98868

It is not clear what you try to do and I feel like taking a risk to answer but anyway..

As I said in my comment, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

And since your J_ID column is Number, there is no point to insert it a string with Convert.ToString(id). Using id (I assume it is an integer) will probably fine.

Also use using statement to dispose your OleDbConnection.

Try like this;

using(OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DB.accdb"))
{
  using(cmd = new OleDbCommand(@"INSERT INTO Nodes ([J_ID],[Node ID],[Node MAC],[Line Quality],[Status]) values(?, ?, ?, ?, ?", conn))
  {
    cmd.Parameters.AddWithValue("@id", id);
    cmd.Parameters.AddWithValue("@nodeid", 0);
    cmd.Parameters.AddWithValue("@nodemac", BitConverter.ToString(mac));
    cmd.Parameters.AddWithValue("@line", 0);
    cmd.Parameters.AddWithValue("@status", "Join");
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

Also think Steve's suggestion in his comment.

Upvotes: 1

Related Questions