如何使用c#执行多个SQL命令

时间:2017-07-04 09:20:42

标签: c# sql

我试图使用这段代码在一个连接中运行两个命令,我无法做到,这是我的代码:

<a href="example.pdf?pk_campaign=pdf201707" class="piwik_download">Download pdf</a>

我的问题最有可能出现在我的行​​中:

using (SqlConnection connection = new SqlConnection(""))
{           
    string query = "SELECT DISTINCT quatro, tres FROM todos_cp ORDER BY quatro, tres ";

    using (SqlCommand RetriveCommand = new SqlCommand(query, conn))
    {
        conn.Open();
        SqlDataReader reader = RetriveCommand.ExecuteReader();

        while (reader.Read())
        {
            string coluna = reader.GetString(reader.GetOrdinal("quatro"));
            string coluna1 = reader.GetString(reader.GetOrdinal("tres"));

            Boolean ElementDisplayed;

            try
            {
            }    
            catch (NoSuchElementException i)
            {
                ElementDisplayed = false;
                GDataPicker();
                for (int x = 0; x < dataGridView1.Rows.Count; x++)
                {
                    string query2 = @"INSERT INTO table_teste1(Rua, CodigoPostal, Distrito, Concelho, Freguesia, GPS) VALUES(" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";

                    for (int x = 0; x < dataGridView1.Rows.Count; x++)
                        {
                            string query2 = @"INSERT INTO table_teste1 (Rua, CodigoPostal,Distrito,Concelho,Freguesia,GPS ) VALUES (" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";


                            using(SqlCommand InsertCommand = new SqlCommand(query2,connection))
                            {

                                InsertCommand.CommandText = query2;
                                InsertCommand.ExecuteNonQuery();

                            }
                        }
                }
            }
        }
        conn.Close();       
    }
}

并说我已经拥有一个数据加载器。

非常感谢帮助,提前谢谢!

1 个答案:

答案 0 :(得分:0)

在&#34; query2&#34;中附加第二个命令。由于它是内联查询,Sql会将其视为两个不同的查询(在分号后追加)并将在同一连接中执行