作者BigGreenFly (好大隻的綠色蒼蠅)
看板Visual_Basic
標題Re: [.NET] 請問如何用VB語法將SQL理想要的資料寫ꐠ…
時間Fri Sep 26 22:32:56 2008
※ 引述《fumizuki (矇面加菲獅)》之銘言
: 給你一個範例
: Imports System.Data.SqlClient
: Imports System.IO
: Imports System.Text
: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
: Handles Me.Load
: Dim ConnectionString As String
: Dim cn As New SqlConnection()
: Dim cmd As New SqlCommand, dr As SqlDataReader = Nothing
: Try
: '連線至SQL Server
: ConnectionString = "Data Source=執行個體名稱;" & _
: "Initial Catalog=資料庫名稱;" & _
: "User ID=帳號;Password=密碼;"
: cn.ConnectionString = ConnectionString
: cn.Open()
: '取得資料
: cmd.Connection = cn
: cmd.CommandText = "sql查詢語法"
: dr = cmd.ExecuteReader()
: '讀取並寫入資料至檔案
: Dim sw As New StreamWriter("檔案路徑", True, Encoding.Default)
: Do While dr.Read()
: sw.WriteLine(dr("欄位名稱").ToString())
: Loop
: sw.Close()
: Catch ex As Exception
: '錯誤處理
: Label1.Text = ex.Message
: Finally
: '不管有沒有錯誤,結束時都要關閉連接
: If Not dr Is Nothing AndAlso Not dr.IsClosed Then dr.Close()
: If Not cn Is Nothing AndAlso cn.State <> _
: Data.ConnectionState.Closed Then cn.Close()
: End Try
: End Sub
謝謝大大提供的程式碼
不過當我要撈多個欄位時
ex:
欄位 A123 B123 C123 D123 E123
值 1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
如果說我要撈A~D欄位的話
TXT檔案撈出來會變成
1
2
3
4
5
1
2
3
4
5
.
.
全部都變成一排
而我希望撈出來可以是4排
就像ex那樣
而且每排之間有空格
希望大大能為我解答
感恩>"<
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.120.147.154
1F:推 fumizuki:把每一個資料列中所有欄位的值組合成一個字串再WriteLine 09/27 20:54
2F:→ BigGreenFly:大大 抱歉 把欄位的值串起來我不太懂,如果說我每個 09/27 23:47
3F:→ BigGreenFly:欄位都各有一百個值,假設我今天要撈四個欄位的話, 09/27 23:48
4F:→ BigGreenFly:那就要把這四百個值都串起來嗎? 抱歉我是新手 希望 09/27 23:50
5F:→ BigGreenFly:沒有煩到你 T_T 09/27 23:51