using System;
using System.Data ;
using System.Data.SqlClient;
namespace DataReaderExample
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{SqlConnection thisConnection=new SqlConnection(@"Data Source=(local);Integrated Security=SSPI;" + "Initial Catalog=northwind");
thisConnection.Open();
SqlCommand thisCommand=thisConnection.CreateCommand();
thisCommand.CommandText="SELECT CustomerID,ComanyName FROM Customers";
SqlDataReader thisReader=thisCommand.ExecuteReader();
while(thisReader.Read())
{
Console.WriteLine("\t{0}\t{1}",
 thisReader["CustomerID"],thisReader["CompanyName"]);}



thisReader.Close();
thisConnection.Close(); //
// TODO: 在此处添加代码以启动应用程序
//
}
}
}
帮我看看有错误吗?

解决方案 »

  1.   

    建议将thisConnection.Close()函数放在finally中。即:
    thisConnection.Open();
    try
    {
        ....
    }
    finally
    {
        thisConnection.Close();
    }
      

  2.   

    把thisReader.Close();thisConnection.Close();放到while循环的外面
    在thisReader.Read())还没有完成是你就thisReader.Close();在datareader里是不允许的!
    你最好try()catch()finally{thisReader.Close();thisConnection.Close(); }
      

  3.   

    catch(Exception ex)
    {
    MessageBox.show(ex.Tostring());
    }
      

  4.   

    没有try  catch  。调试好像不可以通过的
      

  5.   

    大哥,你这个Main函数里程序自动生成的东西呢?好像被你删了吧?再说,数据库连接你可以写在Load事件里啊,也可以另外再写一个函数,怎么你直接写在Main函数里了?另外就是你应该加上错误处理语句,这样便于查错