Yovel Zanzuri
Yovel Zanzuri

Reputation: 63

Executing INSERT command into LocalDB

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.

Upvotes: 0

Views: 1180

Answers (1)

pijemcolu
pijemcolu

Reputation: 2605

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);

Upvotes: 1

Related Questions