サーチ…


データベースからフィールドを読み込む

Public Function GetUserFirstName(UserName As String) As String
    Dim Firstname As String = ""
    
    'Specify the SQL that you want to use including a Parameter
    Dim SQL As String = "select firstname from users where username=@UserName"
    
    'Provide a Data Source
    Dim DBDSN As String = "Data Source=server.address;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=UserPassword"

    Dim dbConn As New SqlConnection(DBDSN)

    Dim dbCommand As New SqlCommand(SQL, dbConn)

    'Provide one or more Parameters
    dbCommand.Parameters.AddWithValue("@UserName", UserName)

    'An optional Timeout
    dbCommand.CommandTimeout = 600

    Dim reader As SqlDataReader
    Dim previousConnectionState As ConnectionState = dbConn.State
    Try
        If dbConn.State = ConnectionState.Closed Then
            dbConn.Open()
        End If
        reader = dbCommand.ExecuteReader
        Using reader
            With reader
                If .HasRows Then
                    'Read the 1st Record
                    reader.Read()
                    'Read required field/s
                    Firstname = .Item("FirstName").ToString
                End If

            End With

        End Using

    Catch
        'Handle the error here
    Finally
        If previousConnectionState = ConnectionState.Closed Then
            dbConn.Close()
        End If
        dbConn.Dispose()
        dbCommand.Dispose()

    End Try
    'Pass the data back from the function
    Return Firstname

End Function

上記の関数を使うのは簡単です:

   Dim UserFirstName as string=GetUserFirstName(UserName)

データベースから読み取り、DataTableとして返す単純な関数

この単純な関数は、指定されたSelect SQLコマンドを実行し、その結果をデータセットとして返します。

Public Function ReadFromDatabase(ByVal DBConnectionString As String, ByVal SQL As String) As DataTable
    Dim dtReturn As New DataTable
    Try
        'Open the connection using the connection string
        Using conn As New SqlClient.SqlConnection(DBConnectionString)
            conn.Open()

            Using cmd As New SqlClient.SqlCommand()
                cmd.Connection = conn
                cmd.CommandText = SQL
                Dim da As New SqlClient.SqlDataAdapter(cmd)
                da.Fill(dtReturn)
            End Using
        End Using
    Catch ex As Exception
        'Handle the exception
    End Try


    'Return the result data set
    Return dtReturn
End Function

これで下のコードから上記の関数を実行することができます

Private Sub MainFunction()
    Dim dtCustomers As New DataTable
    Dim dtEmployees As New DataTable
    Dim dtSuppliers As New DataTable


    dtCustomers = ReadFromDatabase("Server=MYDEVPC\SQLEXPRESS;Database=MyDatabase;User Id=sa;Password=pwd22;", "Select * from [Customers]")
    dtEmployees = ReadFromDatabase("Server=MYDEVPC\SQLEXPRESS;Database=MyDatabase;User Id=sa;Password=pwd22;", "Select * from [Employees]")
    dtSuppliers = ReadFromDatabase("Server=MYDEVPC\SQLEXPRESS;Database=MyDatabase;User Id=sa;Password=pwd22;", "Select * from [Suppliers]")

End Sub

上記の例では、SQL Expressインスタンス「SQLEXPRESS」が現在「MYDEVPC」にインストールされており、データベース「MyDatabase」に「Customers」、「Suppliers」および「Employees」テーブルがあり、「sa」ユーザーパスワードが「pwd22」であると想定しています。希望の結果を得るために、設定に従ってこれらの値を変更してください。

スカラデータを取得する

この単純な関数を使用して、正確に1つのフィールドから1つのレコードクエリ結果

Public Function getDataScalar(ssql As String)
    openConnection()

    Try
        Dim q As New MySqlCommand

        q.Connection = db
        q.CommandText = ssql
        getDataScalar = q.ExecuteScalar

    Catch ex As Exception
        'Exception
    End Try
End Function

どうやって使うのですか:

Dim userid as String = getDataScalar("select username from user where userid=99")

変数 'username'は、そのクエリの結果としてフィールドusernameの値で埋められます。



Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow