从Query中提取数据

时间:2014-04-11 23:28:03

标签: sql vb.net ms-access

请教我如何从SQL查询访问数据库中提取数据并将其放入变量持有者?我已经挣扎了一个星期了,我一直在努力,请建议谢谢

这是我到目前为止所做的:

Imports System.Data.OleDb
Public Class ModifyForm
    Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
    Dim conn As New OleDbConnection
    Private Sub MainMenuButton_Click(sender As Object, e As EventArgs) Handles MainMenuButton.Click
        Me.Close()
        Form1.Show()

    End Sub

    Private Sub CloseButton_Click(sender As Object, e As EventArgs) Handles CloseButton.Click
        Me.Close()
        Form1.Close()

    End Sub

    Private Sub DeleteBut_Click(sender As Object, e As EventArgs) Handles DeleteBut.Click

    End Sub

    Private Sub ModifyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the "Company_dbDataSet1.tbl_empinfo" table. You can move, or remove it, as needed.'
        Me.Tbl_empinfoTableAdapter.Fill(Me.Company_dbDataSet1.tbl_empinfo)

    End Sub
    Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged

        Dim empNum As String
        Dim empFname As String
        Dim empLname As String
        Dim empDept As String
        Dim empStat As String
        Dim empYears As String

        empNum = eNumText.Text
        empFname = empFnameText.Text
        empLname = empLnameText.Text
        empDept = DeptText.Text
        empStat = StatText.Text
        empYears = yearstext.Text

        MsgBox(empNum)
        Dim conn As New OleDbConnection
        conn.Open()


        Dim SqlQuerry As String = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
        Dim SqlCommand As New OleDbCommand
        Dim SqlAdapter As New OleDbDataAdapter
        Dim Table As New DataTable

        With SqlCommand
            .CommandText = SqlQuerry
            .Connection = conn

        End With

        With SqlAdapter
            .SelectCommand = SqlCommand
            .Fill(Table)


        End With

        DataGridView1.Rows.Clear()
        For i = 0 To Table.Rows.Count - 1
            With DataGridView1
                .Rows.Add(Table.Rows(i)("EmpID"), (Table.Rows(i)("FirstName")))
            End With

        Next

        'Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"'


        conn.Close()

    End Sub

1 个答案:

答案 0 :(得分:1)

忘记额外的代码,如前所述,您需要做的就是声明变量:

Dim DBID As Integer  ' Or whatever type you're using for the ID field
Dim DBFirstName As String

然后在For / Next循环中,只需使用:

DBID = Table.Rows(i)("EmpID")
DBFirstName = Table.Rows(i)("FirstName")

只有当你要在for / next循环中使用变量时才会这样,否则你将为每条记录覆盖它们。如果您需要存储所有值,则必须使用数组。