0

I have created a local Service-Based database and I'm trying to insert data to it with an INSERT statement:

public void InsertRule(Rule r)
{
    SqlConnection sqlConnection1 = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\RulesDB.mdf;Integrated Security=True;Connect Timeout=30");

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = ("INSERT INTO TblRules (From, To, ExecutablePath) VALUES (@From, @To, @ExecutablePath");

    cmd.Parameters.Add("@From",SqlDbType.DateTime);
    cmd.Parameters["@From"].Value = r.From;

    cmd.Parameters.Add("@To",SqlDbType.DateTime);
    cmd.Parameters["@To"].Value = r.To;

    cmd.Parameters.Add("@ExecutablePath",SqlDbType.Text);
    cmd.Parameters["@ExecutablePath"].Value = r.ExecutablePath;

    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();

    sqlConnection1.Close();
}

I'm getting a SqlException:

Additional information: Incorrect syntax near the keyword 'From'.

Thanks in advance.

3
  • 1
    "@ExecutablePath)" at the end Commented Jun 30, 2016 at 8:43
  • 4
    FROM is a SQL Server reserved keyword and should NOT be used as a column name! If you can't change it, you need to put it into square brackets: [From] as the column name Commented Jun 30, 2016 at 8:44
  • Thanks, that works. but now when i execute this code, it doesnt seems like it updated the database with the new info Commented Jun 30, 2016 at 8:58

1 Answer 1

0

FROM is SQL keywoard, therefore you can't use it in a statement. You should escape it using square brackets [From]. That's what the error is about

That means you need to change this line

cmd.CommandText = ("INSERT INTO TblRules (From, To, ExecutablePath) VALUES (@From, @To, @ExecutablePath");

into

cmd.CommandText = (@"INSERT INTO TblRules ([From], To, ExecutablePath) VALUES (@From, @To, @executablePath);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.