如何从c#中的表中读取单列中的多行? [英] How to read multiple rows in single column from table in c#?

查看:95
本文介绍了如何从c#中的表中读取单列中的多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储过程,它返回特定数据库的数据和日志文件的路径。

sp返回一行和多列。我必须从每一个读取数据行。

SqlDataReader没有帮助我,也可能是我没有理解它的完整实现。



如何阅读所需的行?

欢迎任何解释...



代码:

I have a stored procedure that returns the path of data and log file for a particular database.
The sp returns a single row and multiple columns.I have to read the data from each and every row.
SqlDataReader is not helping me or may be i have not understood it's complete implementation.

How can i read the required rows?
Any explanation is welcomed...

Code:

string dataFilePath;
string logFilePath;
SqlCommand cmdspText = new SqlCommand("GetAllPhysicalPath", conn);
cmdspText.CommandType = CommandType.StoredProcedure;
cmdspText.Parameters.AddWithValue("@txtDatabaseName", userSpecifiedDBNameInTxtBox);
cmdspText.ExecuteNonQuery();
SqlDataReader reader = new SqlDataReader();
while(reader.Read())
{
//what should i write here
}

推荐答案

您在评论中提供的代码是错误的。如果存储过程返回行,则不应使用 ExecuteNonQuery 函数来执行该过程,因为 ExecuteNonQuery 函数仅返回执行存储过程时受影响的行数。



如果存储过程返回某些行,则必须使用 SqlDataAdapter ExecuteReader 。请使用ExecuteReader参考以下代码。



The code that you have provided in comments is wrong. If your stored procedure returns the rows then you should not use ExecuteNonQuery function to execute the procedure because ExecuteNonQuery function returns only the number of row affected while executing your stored procedure.

You have to use SqlDataAdapter or ExecuteReader, if your stored procedure returns some rows. Please refer the below code using ExecuteReader.

 SqlCommand cmdspText = new SqlCommand("GetAllPhysicalPath", conn);
 cmdspText.CommandType = CommandType.StoredProcedure;
 cmdspText.Parameters.AddWithValue("@txtDatabaseName", userSpecifiedDBNameInTxtBox);
// Assign the results to SqlDataReader by executing the ExecuteReader function
 SqlDataReader reader = cmdspText.ExecuteReader();

// While loop will continue to execute until all records in SQLDataReader got read from it one by one. 
 while(reader.Read())
 {
   //write code to fetch results from data reader..
 }
// Close the object of SqlDataReader
reader.Close();





Happy Coding:)



Happy Coding :)


您可以将数据添加到数据表中

You can add you data to a datatable
DataTable dt = new DataTable();
dt.Rows.Add("Mydata1", "Mydata2", "Mydata3", "Mydata4");





在读取循环时会继续添加行





然后你会检索你的数据,





while read your loop will continue adding rows


And then you retreive your data,

int MyCounter = 0

if (dt.Rows.Count > 0)
{

foreach (DataRow dr in dt.Rows)
{
{

string RetreiveData1 = dt.Rows[MyCounter].ItemArray["Mydata1"].ToString();
string RetreiveData2 = dt.Rows[MyCounter].ItemArray["Mydata2"].ToString();
MyCounter += 1;

}
}





您使用MyCounter移动到下一行。





我希望这有帮助!



You use MyCounter to move to next row.


I hope this helps!


这篇关于如何从c#中的表中读取单列中的多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆