DataReader读取数据步骤
1、连接数据源
2、打开连接
3、发出一个SQL查询命令
4、使用DataReader读取并显示数据
5、关闭DataReader和连接
代码如下:
private void DataReaderUse()
{
//1、建立连接
SqlConnection thisConnection = new SqlConnection(sSqlConnection);
//2、打开连接
thisConnection.Open();
//建立SQL查询
SqlCommand thisCommand = thisConnection.CreateCommand();
//3、输入查询语句
thisCommand.CommandText = "select customerID,companyName from customers";
//建立读取
SqlDataReader thisReader = thisCommand.ExecuteReader();
tbValue.Text = "CustomerID" + "CompanyName";
//4、查询并显示数据
while (thisReader.Read())
{
tbValue.Text += "\r\t";
tbValue.Text += thisReader["CustomerID"].ToString().PadRight(10, ' ');
tbValue.Text += thisReader["CustomerID"].ToString();
}
//5、关闭连接
thisReader.Close();
thisConnection.Close();
}
{
//1、建立连接
SqlConnection thisConnection = new SqlConnection(sSqlConnection);
//2、打开连接
thisConnection.Open();
//建立SQL查询
SqlCommand thisCommand = thisConnection.CreateCommand();
//3、输入查询语句
thisCommand.CommandText = "select customerID,companyName from customers";
//建立读取
SqlDataReader thisReader = thisCommand.ExecuteReader();
tbValue.Text = "CustomerID" + "CompanyName";
//4、查询并显示数据
while (thisReader.Read())
{
tbValue.Text += "\r\t";
tbValue.Text += thisReader["CustomerID"].ToString().PadRight(10, ' ');
tbValue.Text += thisReader["CustomerID"].ToString();
}
//5、关闭连接
thisReader.Close();
thisConnection.Close();
}