使用DataReader从mySQL中的多个表中检索数据

时间:2013-02-07 16:28:26

标签: mysql sql vb.net sqldatareader

如何从'DAILY_CALCULATIONS'表中检索数据

  Dim SqlQuery As String = "SELECT WEEKLY_TIMECARD.*,DAILY_CALCULATIONS.*,EMPLOYEE_PROFILES.EMPLOYEE_NUMBER "
    SqlQuery = SqlQuery + " FROM WEEKLY_TIMECARD, DAILY_CALCULATIONS, employee_profiles WHERE employee_profiles.employee_number"
    SqlQuery = SqlQuery + " = WEEKLY_TIMECARD.employee_number AND EMPLOYEE_PROFILES.EMPLOYEE_NUMBER = DAILY_CALCULATIONS.EMPLOYEE_NUMBER AND"
    SqlQuery = SqlQuery + " WEEKLY_TIMECARD.WEEK_NUMBER = DAILY_CALCULATIONS.WEEK_NUMBER AND WEEKLY_TIMECARD.EMPLOYEE_NUMBER ="
    SqlQuery = SqlQuery + "'" + txtENumber.Text + "' AND WEEKLY_TIMECARD.WEEK_NUMBER = '" + CBWeekNum.SelectedItem + "'"

    Try

        con.Open()

        If con.State = ConnectionState.Open Then
            con.ChangeDatabase("shopclocksoftware")
            Command = New MySqlCommand(SqlQuery, con)
            Data = Command.ExecuteReader()

            While Data.Read
                txtHUnits.Text = Data(2).ToString
                txtOUnits.Text = Data(3).ToString
            End While

我看了一下Data.NextResult方法,但我无法正确实现它,任何想法?

1 个答案:

答案 0 :(得分:0)

Dim SqlQuery As String = "SELECT wtc.A, wtc.B, wtc.C, dc.D, dc.E, ep.F, ep.G"
SqlQuery = SqlQuery + " FROM WEEKLY_TIMECARD wtc, DAILY_CALCULATIONS dc, employee_profiles ep "
SqlQuery = SqlQuery + " WHERE ep.employee_number"
SqlQuery = SqlQuery + " = wtc.employee_number AND ep.EMPLOYEE_NUMBER = dc.EMPLOYEE_NUMBER AND"
SqlQuery = SqlQuery + " wtc.WEEK_NUMBER = dc.WEEK_NUMBER AND wtc.EMPLOYEE_NUMBER ="
SqlQuery = SqlQuery + "@ENumber AND wtc.WEEK_NUMBER = @CBWeekNum"

Try
    con.Open()

    If con.State = ConnectionState.Open Then
        con.ChangeDatabase("shopclocksoftware")
        Command = New MySqlCommand(SqlQuery, con)
        Command.Parameters.AddWithValue("@ENumber", txtENumber.Text);
        Command.Parameters.AddWithValue("@CBWeekNum", CBWeekNum.SelectedItem);

        Data = Command.ExecuteReader()

        Dim aOrdinal As Integer = reader.GetOrdinal("a")
        Dim bOrdinal As Integer = reader.GetOrdinal("b")

        While Data.Read
            txtHUnits.Text = Data.GetString(aOrdinal)
            txtOUnits.Text = Data.GetString(bOrdinal)
        End While
....
Exit Try

有几点需要注意:

  1. 我更改了SQL以使用别名,并返回显式字段名称。使用*通常是一个坏主意,特别是如果您实际上只需要列的子集。
  2. 现在查询参数化,因此您不会对SQL注入攻击开放
  3. 我使用GetOrdinal来定位结果集中任何列的位置。这是次要的优化。
  4. 如果要返回的列是字符串,请调用GetString。否则你可以像以前一样打电话。
  5. 显然我现在没有您的列名,所以SQL不起作用,但您应该明白这一点。