1

I have this code below which should save data from datagridview dtg_ksluzby to sql table KLISLUZ, but it says that:

Embedded statement cannot be declarition or labeled statemnt.

for(int i=0; i< dtg_ksluzby.Rows.Count;i++)
    SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz'" + dtg_ksluzby.Rows[i].Cells["text"].Value +"', '" + dtg_ksluzby.Rows[i].Cells["pocet"].Value +"'",spojeni);
  prikaz2.ExecuteNonQuery();
1
  • 4
    You're open for sql-injection. Use parameters. Commented Jul 17, 2013 at 11:46

2 Answers 2

4

First of all, you should always use parameterized queries, this kind of string concatenations are open for SQL Injection attacks.

Try like this;

for(int i=0; i< dtg_ksluzby.Rows.Count;i++)
{
    using(SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz VALUES(@p1, @p2)",spojeni))
    {
      prikaz2.Parameters.AddWithValue("@p1", dtg_ksluzby.Rows[i].Cells["text"].Value);
      prikaz2.Parameters.AddWithValue("@p2", dtg_ksluzby.Rows[i].Cells["pocet"].Value);
      prikaz2.ExecuteNonQuery();
    }
}

As an alternative which Tim pointed, you can reuse the same SqlCommand for your all values which you just need to use SqlParameterCollection.Clear() method after you execute your command.

Like;

using(SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz VALUES(@p1, @p2)",spojeni))
{
    for(int i=0; i< dtg_ksluzby.Rows.Count;i++)
    {
          prikaz2.Parameters.AddWithValue("@p1", dtg_ksluzby.Rows[i].Cells["text"].Value);
          prikaz2.Parameters.AddWithValue("@p2", dtg_ksluzby.Rows[i].Cells["pocet"].Value);
          prikaz2.ExecuteNonQuery();
          prikaz2.Parameters.Clear();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 ... or reuse the same SqlCommand and call prikaz2.Parameters.Clear first.
2

Your query is wrong (also use Parametrized Queries)

Fixed query:

"INSERT INTO klisluz values('" + dtg_ksluzby.Rows[i].Cells["text"].Value +"', '" + dtg_ksluzby.Rows[i].Cells["pocet"].Value +"')"

Fixed code:

using (SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz values('@val1', '@val2')",spojeni))
{
  for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
  {
    prikaz2.Parameters.Clear();
    prikaz2.Parameters.AddWithValue("@val1", dtg_ksluzby.Rows[i].Cells["text"].Value);
    prikaz2.Parameters.AddWithValue("@val2", dtg_ksluzby.Rows[i].Cells["pocet"].Value);
    prikaz2.ExecuteNonQuery();
  }
}

1 Comment

I fixed his query and showed how to use parameters properly, there is nothing wrong with his loop, but I assume it would be better to answer fully :)

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.