顯示具有 vs2005 標籤的文章。 顯示所有文章
顯示具有 vs2005 標籤的文章。 顯示所有文章

[程式]VB.Net2.0資料庫通用存取函式

序言

在VS2005建立VB專案(或Web網站)後,若要進行資料庫存取,我個人比較習慣將連線字串寫在設定檔app.config(或web.config)下。

不過VB專案預設是不會產生這個檔,而且在程式中若要取得連線字串的設定也要對專案的參考進行設定。

以下記錄下我做的設定,並把資料庫存取程式簡化為函式。

開發環境

  • VB.Net 2.0 (VS2005)
  • MSSQL2005 Express

專案設定

  • 建立專案後預設的專案屬性下,參考的元件如下圖:

  • 下面的程式中會用到【ConfigurationManager】這個物件來取得設定檔的連線字串,所以我們需要加入【System.Configuration】這個元件:

    點選加入,在.Net分頁下找到【System.Configuration】這個元件
  • 再來要在專案加入新項目【應用程式組態】,名稱用預設的【app.config】就可以了:

  • 編輯app.config,在【configuration】標籤內加入連線字串的設定如:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    ...
    <connectionStrings>
    <add name="MSSQLDB1"
    connectionString="Data Source=localhost;Initial Catalog=MyTestDB;Integrated Security=True"
    providerName="System.Data.SqlClient" />
    <add name="MSSQLDB2"
    connectionString="Data Source=127.0.0.1;Initial Catalog=MyTestDB;User ID=sa;Password=1234"
    providerName="System.Data.SqlClient" />
    </connectionStrings>
    ...

通用存取函式類別


Imports System.Data.SqlClient
Imports System.Configuration
Public Class DBAccessFunc
    ''' <summary>
    ''' 從ConfigurationManager中的ConnectionStrings找出Initial Catalog
    ''' </summary>
    ''' <param name="ConnName">ConnectionStrings名稱(String)</param>
    ''' <returns>回傳資料庫名稱</returns>
    ''' <remarks>從ConfigurationManager中的ConnectionStrings找出Initial Catalog</remarks>
    Public Shared Function getDBName(ByVal ConnName As String) As String
        Dim val As String = ""
        Dim ConnString As String = ConfigurationManager.ConnectionStrings(ConnName).ConnectionString
        Dim i As Integer = ConnString.IndexOf("Initial Catalog=")
        If i > -1 Then
            val = ConnString.Substring(i + "Initial Catalog=".Length)
            i = val.IndexOf(";")
            If i > -1 Then
                val = val.Substring(0, i)
            End If
        End If
        Return val
    End Function

    Public Shared Function getConnString(ByVal ConnName As String) As String
        Return ConfigurationManager.ConnectionStrings(ConnName).ConnectionString
    End Function


    Public Shared Function getConn(ByVal ConnName As String) As SqlConnection
        Return New SqlConnection(getConnString(ConnName))
    End Function
    ''' <summary>
    ''' 查詢資料庫
    ''' </summary>
    ''' <param name="cn">連線</param>
    ''' <param name="sql">查詢內容</param>
    ''' <returns>回傳查詢結果的DataTable</returns>
    ''' <remarks>查詢資料庫並回傳查詢結果的DataTable</remarks>
    Public Shared Function getTable(ByRef cn As SqlConnection, ByRef sql As String, Optional ByVal isColseConn As Boolean = True) As Data.DataTable
        Dim da As New SqlDataAdapter(sql, cn)
        Dim dt As New Data.DataTable("dt_xml")
        Try
            If cn.State = ConnectionState.Closed Then cn.Open()
            da.SelectCommand.CommandTimeout = 36000000
            da.Fill(dt)
        Catch ex As Exception
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        End Try
        If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        Return dt
    End Function

    ''' <summary>
    ''' 執行命令
    ''' </summary>
    ''' <param name="cn">連線</param>
    ''' <param name="sql">查詢內容</param>
    ''' <returns>回傳受影響的資料筆數</returns>
    ''' <remarks>執行命令並回傳受影響的資料筆數</remarks>
    Public Shared Function doCmd(ByRef cn As SqlConnection, ByRef sql As String, Optional ByRef param() As SqlParameter = Nothing, Optional ByVal isColseConn As Boolean = True) As Integer
        Dim result As Integer = 0
        Dim cmd As New SqlCommand
        Try
            cmd.Connection = cn
            cmd.CommandText = sql
            If Not param Is Nothing Then
                cmd.Parameters.AddRange(param)
            End If
            cmd.CommandTimeout = 36000000
            If cn.State = ConnectionState.Closed Then cn.Open()
            result = cmd.ExecuteNonQuery()
        Catch ex As Exception
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        Finally
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        End Try
        Return result
    End Function


    ''' <summary>
    ''' 取得單一資料
    ''' </summary>
    ''' <param name="cn">連線</param>
    ''' <param name="sql">查詢內容</param>
    ''' <returns>回傳受影響的資料筆數</returns>
    ''' <remarks>執行命令並回傳受影響的資料筆數</remarks>
    Public Shared Function doScalar(ByRef cn As SqlConnection, ByRef sql As String, Optional ByRef param() As SqlParameter = Nothing, Optional ByVal isColseConn As Boolean = True) As Object
        Dim result As Object = Nothing
        Dim cmd As New SqlCommand
        Try
            cmd.Connection = cn
            cmd.CommandText = sql
            If Not param Is Nothing Then
                cmd.Parameters.AddRange(param)
            End If
            cmd.CommandTimeout = 36000000
            If cn.State = ConnectionState.Closed Then cn.Open()
            result = cmd.ExecuteScalar()
        Catch ex As Exception
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        Finally
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        End Try
        Return result
    End Function

    Public Function executeStoredProcedure(ByRef cn As SqlConnection, ByVal procedure As String, Optional ByRef param As SqlParameter() = Nothing, Optional ByRef output As SqlParameter() = Nothing, Optional ByVal isColseConn As Boolean = True) As Integer
        Dim result As Integer = 0
        Dim cmd As New SqlCommand(procedure, cn)
        Try

            cmd.CommandText = procedure
            cmd.CommandTimeout = 36000000
            cmd.CommandType = CommandType.StoredProcedure
            If Not param Is Nothing Then cmd.Parameters.AddRange(param)
            If Not output Is Nothing Then
                For Each o As SqlParameter In output
                    o.Direction = ParameterDirection.Output
                Next
                cmd.Parameters.AddRange(output)
            End If

            '開啟資料庫連線
            If cn.State = ConnectionState.Closed Then cn.Open()
            '設定變數儲存受影響資料列
            result = cmd.ExecuteNonQuery()
        Catch ex As Exception
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
            Throw ex
        Finally
            cmd.Parameters.Clear()
            If isColseConn And cn.State = ConnectionState.Open Then cn.Close()
        End Try
        Return result
    End Function
End Class


使用範例程式

Dim connStr1 As String = DBGenFunc.getConnStr("MSSQLDB1")
Dim sourceTable As String() = {"[" & DBGenFunc.getDBName("MSSQLDB1") & "].[dbo].[" & "MyTestTab" & "]", _
"[" & DBGenFunc.getDBName("MSSQLDB1") & "].[dbo].[" & "MyContentTab" & "]"}
Dim param() As SqlClient.SqlParameter = {New SqlClient.SqlParameter("P0", SqlDbType.VarChar)}
Dim sql As String

Dim title As String

Console.WriteLine("doCmdScalar Start:")
sql = "SELECT Title" & vbCrLf & _
" FROM " & sourceTable(0) & "" & vbCrLf & _
" WHERE SN=@P0"
param(0).Value = 1
title = DBGenFunc.doCmdScalar(connStr1, sql, param)
Console.WriteLine("doCmdScalar" & vbTab & title)

Console.WriteLine("getTable Start:")
sql = "SELECT Title" & vbCrLf & _
" FROM " & sourceTable(0) & "" & vbCrLf
Dim dt As DataTable = DBGenFunc.getTable(connStr1, sql)
For Each r As DataRow In dt.Rows
title = r.Item(0)
Console.WriteLine("getTable" & vbTab & title)
Next

Console.WriteLine("getTableToArray Start:")
Dim data As String() = DBGenFunc.dataTableToArray(Of String)(dt, 0)
For Each r As String In data
title = r
Console.WriteLine("getTable" & vbTab & title)
Next

Console.WriteLine("doCmd Start:")
sql = "INSERT INTO " & sourceTable(0) & "" & vbCrLf & _
"VALUES(@P0,@P1)"
param = New SqlClient.SqlParameter() {New SqlClient.SqlParameter("P0", SqlDbType.VarChar), _
New SqlClient.SqlParameter("P1", SqlDbType.VarChar)}
param(0).Value = "TNew"
param(1).Value = "SNew"
title = DBGenFunc.doCmd(connStr1, sql, param)
Console.WriteLine("doCmd" & vbTab & title)

Console.WriteLine("getReader Start:")
sql = "SELECT Title, Subject" & vbCrLf & _
" FROM " & sourceTable(0) & "" & vbCrLf
Dim dr As SqlClient.SqlDataReader = DBGenFunc.getReader(connStr1, sql)
While dr.Read()
title = dr.Item(0)
Console.WriteLine("getReader" & vbTab & title & vbTab & dr.Item(1))
End While
DBGenFunc.closeReader()

執行結果

doCmdScalar Start:
doCmdScalar T1
getTable Start:
getTable T1
getTable T2
getTable T3
getTable TNew
getTableToArray Start:
getTable T1
getTable T2
getTable T3
getTable TNew
doCmd Start:
doCmd 1
getReader Start:
getReader T1 S1
getReader T2 S2
getReader T3 S3
getReader TNew SNew
getReader TNew SNew

[記事]Asp.Net讓人有像VB一樣簡單的印象

很久沒在這寫文章了~因為沒碰到什麼特別想寫的題材~

不過這段時間我也沒閒著~

因緣際會下~我用ASP.Net 2.0寫了兩個很簡陋的網站~

一個是免費幫某佛教講堂寫的成績單系統~(這樣有算做功德嗎?)

因為他們裡面其實沒什麼會寫程式的人~

就有人用Access要提供師父能將學員資料還有課程成績輸入進去~

他原本還用Access的一些表單來讓人容易點輸入資料~

可是後來發現沒辦法輸出一個個人歷年成績單的格式~

那時透過我老爸找上了我~

想要我用VB (後來我才知道他應該是在說ASP.Net) 來幫他處理這個問題~


另一個是幫某大學資科的學生寫的網站~(小小收點工本費~)

他說他的指導老師希望他能學個語言~

然後做個完整的系統~

他就開始上網找別人的範例~

結果在藍色小鋪找到我三年多前以VS2003寫的一個網站~

他覺得功能符合他的需求~

但因為他要用VS2005開發~又有點趕時間~

最後找上我這個原始開發者~希望我能用VS2005的控制項做出那個網站的功能~


第二個Case我用三天完成了~

第一個Case因為需求是慢慢增加的~加上我是有空才做~有時要問需求又找不到人~

所以還在弄~


在這兩個Case中~我發現一件事~

從ASP .Net到了ASP .Net 2.0後~

這個網站的開發方式與工具~已經開始讓人有如同VB 6的那種感覺~

【夠簡單~夠直覺】

至少門檻已經降到逐夠讓一個業餘想寫寫小網站的人~

可以在拖拉點選之間做出一個功能還不算太差的東西~


為什麼我會說像VB 6呢~

相信曾經經過VB 6極盛時期~而且玩過VB 6的人~

應該跟我有相同感覺~

【居然可以這麼容易寫出一個視窗程式】

當然~這要看你玩多大啦~

但至少是個門檻夠低的開發工具~


而ASP.Net 2.0能像當初的VB 6一樣~

給連VB怎麼寫的人都不知道的狀況下~居然會在有需求時~

跟我說一句~

【要做這樣東西,好像可以用ASP.Net吧】

或是

【聽說ASP.NET2.0配合2005可以省很多程式碼】

重點除了它真的把做網站搞的很像VB 6的開發模式外~

另外還在後來提供Visual Web Developer 2005 Express這個免費版的開發工具~

讓這件事變的更沒理由不用看看~

我並不是絕對挺微軟或是其他公司~

而我自己也曾與朋友討論過各種語言的開發特性與缺點~

甚至最近也剛碰ROR~

但就一個簡單快速的概念驗證(prove of concept)的網站開發而言~

ASP.Net確實有相當程度的吸引力讓我使用它~

這是我的看法~

VS2005(.Net)非同步呼叫Web Services

.Net Framework 2.0所提供的開發環境中,提供了簡單的方式讓你用非同步的方法呼叫Web Services

它使用MothodName後方加上Async名稱的函式當做呼叫方法,然後另外寫一個函式處理呼叫的回傳值

我想背後原理應該不脫離使用執行序(Thread)來達到這樣的功能。

參考資料中有微軟的範例,但它的做法如果用在連續呼叫的話可能會有些問題,而且沒有C#的範例,

所以我稍做修改成我需要的版本

開發環境

  • Microsoft Visual Studio 2005 (.Net Framework 2.0)
  • 專案類型:Windows 應用程式
  • 已有一個簡單的Web Service,該Service中有個函式: Function hello(ByVal name As String) As String
  • 我將Web Service加到名為wsServer的Web參考中
  • 我在畫面中用一個多行的TextBox叫resultOut來顯示呼叫與回應的資訊

C#

  //CallMyWSAsync用來New起Web service的實體,指定處理回應的函式,然後呼叫Web Service
 private void CallMyWSAsync(string value)
 {
  //New起Web service的實體
  wsServer.WebService ws = new wsServer.WebService();
  //指定處理回應的函式
  ws.helloCompleted += new wsServer.helloCompletedEventHandler(getCompletedHandler);
  //resultOut來顯示呼叫的資訊
  string o = "ID=" + ws.GetHashCode() + " Start, value=" + value;
  o = DateTime.Now.ToString() + "\r\n" + o;
  resultOut.Text = o + "\r\n" + resultOut.Text;
  resultOut.Text = "\r\n" + resultOut.Text;
  //呼叫Web Service
  ws.helloAsync(value);

 }

 //getCompletedHandler用來處理回應
 private void getCompletedHandler(object sender, wsServer.helloCompletedEventArgs e)
 {
  string o;
  if (e.Error == null)
  {
   o = "ID=" + sender.GetHashCode() + " Done, Result: " + e.Result; //e.Result可取得回應的物件
  }
  else
  {
   o = e.Error.Message;
  }
  //resultOut來顯示回應的資訊
   o = DateTime.Now.ToString() + "\r\n" + o;
  resultOut.Text = o + "\r\n" + resultOut.Text;
  resultOut.Text = "\r\n" + resultOut.Text;
 } 

VB


   'CallMyWSAsync用來New起Web service的實體,指定處理回應的函式,然後呼叫Web Service
   Sub CallMyWSAsync(ByVal value As String)
       'New起Web service的實體
       Dim ws As New wsServer.WebService
       '指定處理回應的函式
       AddHandler ws.helloCompleted, AddressOf getCompletedHandler
       'resultOut來顯示呼叫的資訊
       Dim o As String = "ID=" + ws.GetHashCode() + " Start, value=" + value
       o = DateTime.Now.ToString() + vbCrLf + o
       resultOut.Text = o + vbCrLf + resultOut.Text
       resultOut.Text = vbCrLf + resultOut.Text
       '呼叫Web Service
       ws.helloAsync(value)

   End Sub
   'getCompletedHandler用來處理回應
   Private Sub getCompletedHandler(ByVal sender As Object, ByVal e As wsServer.helloCompletedEventArgs)
       Dim o As String
       If e.Error Is Nothing Then
           o = "ID=" + sender.GetHashCode() + " Done, Result: " + e.Result 'e.Result可取得回應的物件
           o = DateTime.Now.ToString() + vbCrLf + o
           resultOut.Text = o + vbCrLf + resultOut.Text
           resultOut.Text = vbCrLf + resultOut.Text
       Else
           o = e.Error.Message
       End If
       'resultOut來顯示回應的資訊
       o = DateTime.Now.ToString() + vbCrLf + o
       resultOut.Text = o + vbCrLf + resultOut.Text
       resultOut.Text = vbCrLf + resultOut.Text
   End Sub

後言

這是我第一次寫C#的程式,因為我想順便體驗C#開發起來有何不同,

我在查資料時,還有看到ASP.Net的網頁也可以設為Async,不過會有什麼結果我沒試過,下回有空再寫寫札記吧

參考資料

用.Net Compact Framework 1.1開發時開外部程式

之前有學弟為了在一台有Win CE環境的PDA上開發應用程式傷腦筋

原因是Visual Studio 2005提供.Net Compact Framework 2.0 無法發佈在比較舊版的Win CE上,

所以就使用.Net Compact Framework 1.1在開發,然後就出現了一個問題,

要呼叫外部程式的話,去MSDN找現有函式只有2.0的才有,

1.1的就要用我下面說的東西了~

PS.我在Google上找 VB 範例,能直接用不會有錯的都不在前面的搜尋結果,讓我花了不少功夫~

開發環境

  • Microsoft Visual Studio 2005
  • 語言:VB

程式功能

  • 在.Net Compact Framework 1.1的環境下,使用VB程式呼叫外部的程式
  • 等外部程式結束後,才繼續往下一行程式執行

開發要點

開一個模組,來放下面的程式

Module MyProcessCreater



 Declare Function CreateProcess Lib "CoreDll.dll" (ByVal imageName As String, ByVal cmdLine As String, ByVal lpProcessAttributes As IntPtr, ByVal lpThreadAttributes As IntPtr, ByVal boolInheritHandles As Int32, ByVal dwCreationFlags As Int32, ByVal lpEnvironment As IntPtr, ByVal lpszCurrentDir As IntPtr, ByVal si As Byte(), ByVal pi As ProcessInfo) As Integer



 Declare Function WaitForSingleObject Lib "CoreDll.dll" (ByVal Handle As IntPtr, ByVal Wait As Int32) As Int32



 Declare Function GetLastError Lib "CoreDll.dll" () As Int32



 Declare Function CloseHandle Lib "CoreDll.dll" (ByVal Handle As IntPtr) As Int32





 Public Class ProcessInfo

     Public hProcess As IntPtr

     Public hThread As IntPtr

     Public ProcessId As Int32

     Public ThreadId As Int32

 End Class 'ProcessInfo





 Public Function CreateProcess(ByVal ExeName As String, ByVal CmdLine As String, ByVal pi As ProcessInfo) As Boolean

     Dim INFINITE As Int32

     INFINITE = &HFFFFFFFF



     Dim WAIT_OBJECT_0 As Int32 = 0

     Dim result As Int32



     If pi Is Nothing Then

         pi = New ProcessInfo

     End If

     Dim si(128) As Byte



     result = CreateProcess(ExeName, CmdLine, IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, si, pi) '呼叫外部程式

     If 0 = result Then

         Return False

     End If

     result = WaitForSingleObject(pi.hProcess, INFINITE) '等外部程式結束

     CloseHandle(pi.hThread)

     CloseHandle(pi.hProcess)

     If WAIT_OBJECT_0 <> result Then

         Return False

     End If

     Return True

 End Function



End Module 

然後在要呼叫的地方加入以下程式

CreateProcess("要呼叫的程式路徑", "", Nothing)

第一個參數:"要呼叫的程式路徑" 如"\Windows\iexplore.exe"

第二個參數:是外部程式用的參數

第三個參數:我也不清處怎麼用

參考資料

'方法1
returnID = Shell("D:\run.txt", vbNormalFocus)

'方法2
System.Diagnostics.Process.Start ("D:\run.txt")

'方法3
Dim myProcess As Process = System.Diagnostics.Process.Start
("D:\run.txt")
MessageBox.Show(myProcess.ProcessName)

'方法4
Dim psInfo As New _
System.Diagnostics.ProcessStartInfo _
("D:\run.txt")
psInfo.WindowStyle = _
System.Diagnostics.ProcessWindowStyle.Normal
Dim myProcess As Process = _
System.Diagnostics.Process.Start(psInfo)

'方法5
Dim myProcess As System.Diagnostics.Process = _
new System.Diagnostics.Process()
myProcess.StartInfo.FileName = _
"D:\run.txt"
myProcess.StartInfo.WindowStyle = _
System.Diagnostics.ProcessWindowStyle.Normal
myProcess.Start

這裡是關於技術的手札~

也歡迎大家到

倫與貓的足跡



到噗浪來

關心一下我唷!
by 倫
 
Copyright 2009 倫倫3號Beta-Log All rights reserved.
Blogger Templates created by Deluxe Templates
Wordpress Theme by EZwpthemes