SqlDataReader 讀取資料

1 篇文章 / 0 new
author
SqlDataReader 讀取資料
SqlCommand sqlComad = new SqlCommand();
sqlComad.CommandType = CommandType.Text;
sqlComad.Connection = objConn;
sqlComad.CommandText = "select * from "+tableName;
SqlDataReader dataReader = sqlComad.ExecuteReader();//資料讀取
 
DataTable dt = new DataTable();
int fieldCcount = dataReader.FieldCount;//欄位數量
//設定欄位
for (int i= 0; i < fieldCcount; i++)
    dt.Columns.Add(dataReader.GetName(i));
//填入資料
String[] rowItem = new String[fieldCcount];
while (dataReader.Read())
{   //讀出每行資料
    for (int i = 0; i < fieldCcount; i++)
        rowItem[i] = dataReader[i].ToString();
        //rowItem[i] = dataReader[dataReader.GetName(i)].ToString();
        //dataReader[x], x:可為index或欄位名稱(無大小寫區分)
    dt.Rows.Add(rowItem);//將行資料加入資料表
}
dataReader.close();
this.dataGridView1.DataSource = dt;
VB
Dim connStr As String = Global.System.Configuration.ConfigurationManager.ConnectionStrings("CTCI_HSE_ConnectionString").ConnectionString
Using dbConn As New SqlConnection(connStr)
    dbConn.Open()
    Dim sc As SqlCommand = dbConn.CreateCommand()
    sc.CommandText = "select user_name from [user]"
    Dim nList As String = ""
    Dim dReader As SqlDataReader = sc.ExecuteReader() '資料讀取
    If dReader IsNot Nothing AndAlso dReader.HasRows Then
        While dReader.Read()    '讀出每行資料
            nList = nList & dReader("user_name").ToString() & ","
        End While
        dReader.Close() '一定要關閉
        Console.WriteLine(nList)
    End If
End Using
from http://msdn.microsoft.com/zh-tw/library/haa3afyz%28v=vs.110%29.aspx?cs-s...
Free Web Hosting