如何获得sql连接

时间:2010-03-30 21:16:30

标签: vb.net sqlconnection

FS_Setting是一个VB类,它具有连接的所有细节,即:

Public Class FS_Setting
    Public Function Get_RS_Connection() As SqlConnection
        Try
            Get_RS_Connection = New SqlConnection("Data Source=***********;User ID=sa;Password=*****;database=*********")
                             Catch ex As System.Exception
            Throw New System.Exception("Get_RS_Connection Error:" + ex.Message)
        End Try
    End Function

我需要在另一个类中调用函数Get_RS_Connection(),而不是再次获取连接和硬编码....我想调用声明SQL连接的上面的类

Namespace FS_Library
       Public Class FS_Errorlog
        Inherits FS_BaseClass
Try

    **cn = New SqlConnection("Data Source=***********;UserID=sa;Password=*****;database=*********")**
    cmd = New SqlCommand("dbo.FS_ErrorLog_ADD", cn)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.CommandTimeout = Convert.ToInt32(ConfigurationSettings.AppSettings("Command_Timeout"))
    Me.AddParameter(cmd, "@p_tableKey", SqlDbType.Int, tableKey)
    Me.AddParameter(cmd, "@p_FunctionCode", SqlDbType.Int, FunctionCode)
    Me.AddParameter(cmd, "@p_TableAlias", SqlDbType.VarChar, TableAlias)
    Me.AddParameter(cmd, "@p_ValidationCode", SqlDbType.Int, ValidationCode)
    If Filename = "" Then
        Filename = "N/A"
    End If
    Me.AddParameter(cmd, "@p_FileName", SqlDbType.VarChar, Filename)
    Me.AddParameter(cmd, "@p_Message", SqlDbType.VarChar, Message)
    Me.AddParameter(cmd, "@p_CreateUser", SqlDbType.VarChar, userID)
    Me.AddParameter(cmd, "@p_UserActionID", SqlDbType.UniqueIdentifier, UserActionID)
    cn.Open()

1 个答案:

答案 0 :(得分:0)

以下代码更改将使代码可以从项目中的任何位置调用,而无需显式声明该类:

Public Class FS_Setting
    Public Shared Function Get_RS_Connection() As SqlConnection
        Try
            Get_RS_Connection = New SqlConnection("Data Source=***********;User ID=sa;Password=*****;database=*********")
         Catch ex As System.Exception
            Throw New System.Exception("Get_RS_Connection Error:" + ex.Message)
        End Try
    End Function

而不是:

cn = New SqlConnection("Data Source=***********;UserID=sa;Password=*****;database=*********")**

您可以使用:

cn =FS_Setting.Get_RS_Connection