简体   繁体   中英

SqlCommand INSERT INTO from datagridview to SQL DB table

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM