C# ADO.NET-数据读取错误
我试图将数据库中某列的数据显示到我的rich textbox上,但我混淆了DataSet和DataReader-我知道下面的大部分代码都是正确的,我只得到两行包含错误的代码,我不确定为什么:C# ADO.NET-数据读取错误,c#,ado.net,datareader,dataadapter,C#,Ado.net,Datareader,Dataadapter,我试图将数据库中某列的数据显示到我的rich textbox上,但我混淆了DataSet和DataReader-我知道下面的大部分代码都是正确的,我只得到两行包含错误的代码,我不确定为什么: // Create a connection string string ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\\Documents and Settings\\Harley\\D
// 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();
}