【问题标题】:ADO.NET - DataRead ErrorADO.NET - 数据读取错误
【发布时间】:2011-06-06 17:21:12
【问题描述】:

我正在尝试将数据库中的列中的数据显示到富文本框中,但我在 DataSet 和 DataReader 之间搞混了 - 我知道下面的大部分代码是正确的,我只得到包含错误的两行,我不知道为什么:

// Create a connection string
            string ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\\Documents and Settings\\Harley\\Desktop\\Test.accdb");
            string SQL = "SELECT * FROM Paragraph";

            // create a connection object
            SqlConnection conn = new SqlConnection(ConnectionString);

            // Create a command object
            SqlCommand cmd = new SqlCommand(SQL, conn);
            conn.Open();

            DataTable dt = new DataTable();
            da.Fill(dt); //ERROR

            // Call ExecuteReader to return a DataReader
            SqlDataReader reader = cmd.ExecuteReader();

            foreach(DataRow reader in dsRtn) //ERROR
            {
                richTextBox = richTextBox.Text + reader[0].ToString();
            }

            //Release resources
            reader.Close();
            conn.Close();

        }

【问题讨论】:

    标签: c# ado.net datareader dataadapter


    【解决方案1】:

    您的每个 sn-ps 都有问题。

    对于您提供的数据适配器实现:

            SqlCommand cmd = new SqlCommand(SQL, conn);
            conn.Open();
    
            DataTable dt = new DataTable();
            da.Fill(dt); //ERROR
    

    您没有将 SqlCommand 对象与您的 DataAdapter 关联,因此它不知道如何填充您的 DataTable。

    至于您的数据读取器实现,

            // Call ExecuteReader to return a DataReader
            SqlDataReader reader = cmd.ExecuteReader();
    
            foreach(DataRow reader in dsRtn) //ERROR
            {
                richTextBox = richTextBox.Text + reader[0].ToString();
            }
    

    你错误地使用了 DataReader 试试这个:

            // Call ExecuteReader to return a DataReader
            SqlDataReader reader = cmd.ExecuteReader();
    
            while( reader.Read() )
            {
                richTextBox = richTextBox.Text + reader[0].ToString();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-26
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      相关资源
      最近更新 更多