【问题标题】:For loop query sql database in asp.net c#asp.net c#中的for循环查询sql数据库
【发布时间】:2014-07-29 03:46:55
【问题描述】:

我不太确定如何使用更适合我的问题的 for 循环或 while 循环。
我需要根据下拉列表中的选定项目和字段 Processed ='False' 查询数据库

然后我的代码在循环中

然后根据下拉列表中的选定项更新数据库,字段已处理变为='True'

我的代码如下,我需要循环在 document.open 和 document.close 中

    protected void GenerateReport(object sender, EventArgs e)
    {
        DataRow dr = GetData("SELECT * FROM OnSiteWorkTx where DocID = " + DropDownListPdf.SelectedItem.Value).Rows[0]; ;
        Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
        Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);

        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
            Phrase phrase = null;
            PdfPCell cell = null;
            PdfPTable table = null;
            BaseColor color = null;

            document.Open();

            //Header Table
            table = new PdfPTable(2);
            table.TotalWidth = 500f;
            table.LockedWidth = true;
            table.SetWidths(new float[] { 0.6f, 0.3f });


            cell = ImageCell("~/pic.jpg", 40f, PdfPCell.ALIGN_LEFT);
            table.AddCell(cell);



            phrase = new Phrase(new Chunk("QAF 018/2\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, BaseColor.BLACK)));
            phrase.Add(new Chunk("On Site Work                        " + "Visit " + dr["VisitNumber"] + "   " + dr["PageNumber"], FontFactory.GetFont("Arial", 15, Font.NORMAL, BaseColor.BLACK)));
            // table.AddCell(PhraseCell(new Phrase("On Site Work", FontFactory.GetFont("Arial", 20, Font.UNDERLINE, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
            cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_RIGHT);
            cell.Colspan = 2;
            cell.PaddingBottom = 13f;
            table.AddCell(cell);



            //Separater Line
            color = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
            DrawLine(writer, 25f, document.Top - 79f, document.PageSize.Width - 25f, document.Top - 79f, color);
            DrawLine(writer, 25f, document.Top - 80f, document.PageSize.Width - 25f, document.Top - 80f, color);
            document.Add(table);


            table = new PdfPTable(2);
            table.SetWidths(new float[] { 2f, 10f });
            table.TotalWidth = 480f;
            table.LockedWidth = true;
            table.SpacingBefore = 15f;
            table.HorizontalAlignment = Element.ALIGN_RIGHT;



            table.AddCell(PhraseCell(new Phrase("Company: ", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            phrase = new Phrase(new Chunk(dr["Company"] + "          " + "           " + "          " + "           " + "           " + "           " + "           " + "Email: " + dr["Email"], FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
            table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
            cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan = 7;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Plant: ", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            phrase = new Phrase(new Chunk(dr["Plant"] + "          " + "           " + "          " + "           " + "           " + "           " + "          " + "Contact Tel: " + dr["ContactTel"], FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
            table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
            cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Contact Person: ", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            phrase = new Phrase(new Chunk(dr["ContactPerson"] + "          " + "           " + "          " + "           " + "           " + "           " + "Fax No: " + dr["FaxNo"], FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
            table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
            cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);
            document.Add(table);
            document.NewPage();

            try
       {    string constring = "Data Source=(local);Initial Catalog=FAUMA;User ID=sa;Password=P@ssw0rd";
            string Query = "update OnSiteWorkTx set Processed = 'True' where Company = '" + DropDownListPdf.Text + "'and Processed = 'False'";
            SqlConnection conDatabase = new SqlConnection(constring);
            SqlCommand cmdDatabase = new SqlCommand(Query, conDatabase);
            SqlDataReader reader;
            conDatabase.Open();
            reader = cmdDatabase.ExecuteReader();

            while (reader.Read())
            {
            }

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {

            conDatabase.Close();

        }
            document.Close();

            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            Response.Clear();


                //Save as Attachment

                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=OnSiteWork.pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
        }


    }

【问题讨论】:

  • 请只留下您的问题的相关代码。您是否需要知道如何更新数据库表 OnSiteWorkTx 中的一组记录?
  • 虽然它没有回答您的问题,但请阅读有关 SQL 注入攻击、绑定参数和 using 块的信息。它将大大改善您的代码。

标签: c# asp.net sql for-loop while-loop


【解决方案1】:

要更新您在下拉列表中选择的公司,您需要这样的东西。

try
{    
     string constring = "Data Source=(local);Initial Catalog=FAUMA;User ID=sa;Password=P@ssw0rd";
     string Query = @"update OnSiteWorkTx set Processed = 1 
                      where Company = @company and Processed = 0";
     using(SqlConnection conDatabase = new SqlConnection(constring))
     using(SqlCommand cmdDatabase = new SqlCommand(Query, conDatabase))
     {
         cmdDatabase.Parameters.AddWithValue("@company", DropDownListPdf.Text);
         conDatabase.Open();
         cmdDatabase.ExecuteNonQuery();
     }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
}

您使用参数化查询而不是字符串连接来准备命令,并仅使用一个 ExecuteNonQuery 来更新公司的所有相关记录。另请注意,将字符串“True”或“False”作为 SQLServer 中位字段的值传递不起作用。你传递 1 表示 True,0 表示 False。

关于对 GetData 方法返回的每一行执行此代码,您可以简单地以这种方式重构您的代码

protected void GenerateReport(object sender, EventArgs e)
{
    DataTable dt = GetData("SELECT * FROM OnSiteWorkTx where DocID = " +
                            DropDownListPdf.SelectedItem.Value);
    foreach(DataRow dr in dt.Rows)
    {
        PrepareDocument(dr);
    }
}

其中 PrepareDocument 是您已经编写的所有代码并且在一行中运行

private void PrepareDocument(DataRow dr)
{
    Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
    Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);

    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
    {
         ...... all the code above, but with the DataRow passed from the calling method
    }
}

【讨论】:

  • 谢谢你,关于在我更新之前循环代码
  • Steve,再次感谢您,我没有注意到准备文档的编辑,我回来查看更新代码。我很感激#ImSoHappy,因为它现在可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多