程序运行时没有错误,但没有给出所需的输出

问题描述:

以下程序从SQL Server 2008表中提取数据,应用一个简单的for循环并记录总记录数。程序编译并运行成功,没有任何错误,但不会将记录总数记录到屏幕上。它不打印任何东西。 的.cs(代码隐藏)是:程序运行时没有错误,但没有给出所需的输出

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.Sql; 
using System.Data.SqlClient; 
using System.Data; 
namespace CountDocs 
{ 
    public partial class Home : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 
     protected void btnCount_Click(object sender, EventArgs e) 
     { 
      SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;"); 
      { 
       using (SqlCommand cmd = new SqlCommand()) 
       { 
        String sql = "select * from dbo.Company"; 
        cmd.Connection = con; 
        cmd.CommandText = sql; 
        con1.Open(); 
        Int32 Total = 0; 
          Total = (Int32)cmd1.ExecuteScalar(); 
          Console.WriteLine(Total); 
        if (con.State == ConnectionState.Open) 
        { 
         con.Close(); 
        } 
        for (int i = 0; i < dt.Rows.Count; ++i) 
        { 
         string companyname; 
         companyname = dt.Rows[i].ItemArray[0].ToString(); 
         SqlConnection con1 = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;"); 
         { 
          using (SqlCommand cmd1 = new SqlCommand()) 
          { 
           String sql1 = "select Count(*) from dbo.Documents where Src=" + "'" + companyname + "'"; 
           cmd1.Connection = con1; 
           cmd1.CommandText = sql1; 
           con.Open(); 
           DataTable dt1 = new DataTable(); 
           Int32 Total = 0; 
           Total = (Int32)cmd1.ExecuteScalar(); 
           Console.WriteLine(Total); 
           if (con.State == ConnectionState.Open) 
           { 
            con.Close(); 
           } 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
} 

由于程序不抛出任何语法错误,我想这可能是一个逻辑上的错误。有人能帮我注意吗?提前致谢。

+1

使用cmd1.ExecuteScalar。没有使用SqlDataAdapter的要点。 ExecuteScalar - 执行查询,并返回查询返回的结果集中第一行的第一列。 – Seminda 2014-10-22 04:18:46

+0

@Seminda你认为SqlDataAdapter导致问题? – 2014-10-22 04:30:29

+0

不,但如果你只需要一列,那么ExecuteScalar就在你身边。它会让你的代码更加简单,并且你可以很容易地识别你的问题。 – Seminda 2014-10-22 22:01:06

系统工作正常,因为如果你写dt1.Rows [0] .ToString()你没有得到单元格的值。这是因为System.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem不会覆盖方法ToString()

我认为你必须使用dt1.Rows[0].ItemArray[3]dt1.Rows[0]["column name"].ToString();

希望这有助于。

+0

我的眼睛刚发现一个错误。循环内部的第二个连接('con1')必须打开和关闭,而不是for循环之外的第一个连接('con')。如此,现在系统运行成功而不产生任何输出。 – 2014-10-22 05:09:39

+0

您的解决方案无法使用。对不起 – 2014-10-22 05:20:38

+0

什么不起作用?你有更多的信息吗?没有评论,你的代码很难读... – BendEg 2014-10-22 05:52:22