查看完整版本: C# 讀取SQL server 單一欄位 請教
頁: [1]

ww22511 發表於 2019-5-18 01:26 AM

C# 讀取SQL server 單一欄位 請教

抱歉 請問  如果 我只想要抓取單一欄位而已然後顯示在 textbox 上
SQL : select 第一 from 資料表 where ID=001;
那我該怎麼接收他 然後放入textbox裡面呢?

<div></div>

皇臾 發表於 2019-5-18 09:53 AM

因為你只是讀取資料,所以我假設你不會有修改的需要。

在 .NET 的環境裡,讀取資料的選擇不只一種,但是較直覺的做法就是用 System.Data.SqlClient 命名空間提供的內建功能,也就是透過 SqlConnection、SqlCommand、SqlDataReader 這幾個物件就能從 SQL Server 中讀取你要的資料。

首先,你要先使用 SqlConnection 連線到資料庫:
string connectionStr = "server=localhost\\sqlexpress;database=Northwind;integrated security=SSPI;";
SqlConnection cn = new SqlConnection(connectionStr);
接著,藉由你的SQL指令,明確指明要讀取資料的範圍:
string qs = "select 第一 from 資料表 where ID=001;";
SqlCommand command = new SqlCommand(qs, cn);
最後,再以 SqlDataReader 將讀取到的資料取出來:
SqlDataReader dr = command.ExecuteReader();
while ((dr.Read()))
{
        TextBox1.Text = dr["第一"].ToString();
}
記得,程式一開始要引用 System.Data.SqlClient 命名空間。
...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

aquarius6913 發表於 2019-6-26 10:09 PM


有2個方式

DataTable.Rows



DataTable.Rows


底下跑迴圈方式取值
foreach (DataRow row in table.Rows)
{

    row ' 用 column index 存取欄位內容

    row ' 用 column name 存取欄位內容
}
頁: [1]