繁体   English   中英

ADO.NET-DataRead错误

[英]ADO.NET - DataRead Error

我正在尝试将数据库中的列中的数据显示到富文本框中,但是我在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();

        }

您的每个摘录都有一个问题。

对于数据适配器实现,您提供了以下内容:

        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();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM