单击“列表框”时如何从数据库中获取记录

时间:2014-09-12 03:22:24

标签: delphi delphi-xe2

我有两个列表框和两个表,一个表由query_no和query_name组成,另一个表是query_no和Query_item。现在,如果我要插入记录,那么它可能是:

    Table 1
    Query_no   Query_name
    101        Query1

    Table 2
    Query_no    Query_item
    101         Item1
    101         Item2

我的listbox1显示来自table1的所有query_name,我放了一个双击事件。如果我从listbox1双击Query1,那么具有相同query_no的所有项目将显示在我的listbox2中。

任何人都可以帮我这么做吗?提前致谢。

到目前为止这是我的代码:

procedure TQueryForm.ListBox3DblClick(Sender: TObject);
var
  i : integer;
begin
  for i := 0  to listbox3.Items.Count-1 do
    if listbox3.Selected[i] then
      sqtrans.SQL.Text := 
        'Select QUERY_ITEMS FROM QUERY_ITEM c '+
        'INNER         JOIN      QUERYTABLE t on t.QUERY_NO=c.QUERY_NO '+
        'where t.QUERY_NO=c.QUERY_NO';
  try
    sqtrans.Open;
    listbox2.Items.Clear;
    while not sqtrans.Eof do
    begin
      listbox2.Items.Add(sqtrans.FieldByName('QUERY_ITEMS').AsString);
      sqtrans.Next;
    end;
  finally
    sqtrans.close;
  end;
end;

1 个答案:

答案 0 :(得分:1)

您无法使用ListBox1中的值或正确形成SQL WHERE子句以仅检索所需的数据。 (您当前返回Query_No相同的两个表中的所有行,而不考虑它是否与ListBox1中指示的名称匹配。)

这样的事情应该起作用:

procedure TQueryForm.ListBox3DblClick(Sender: TObject);
var
  i : integer;
  SearchVal: string;
begin
  if ListBox1.ItemIndex = -1 then 
    Exit;

  // Disable UI update for ListBox while items are being removed/added
  // to avoid flickering (and improve performance if there are a lot of
  // items).
  ListBox2.Items.BeginUpdate;
  try
    ListBox2.Items.Clear;

    // This presumes that the order of the items in ListBox1
    // are in the same order as the rows in the DB. In other 
    // words, it presumes that the first item in the ListBox
    // is 
    SearchVal := ListBox1.Items[ListBox1.ItemIndex];

    // Populate query, creating parameter that will contain the
    // selected item text from above
    sqTrans.SQL.Text := 'Select Query_Items FROM Query_Item c'#13 +
                        'INNER JOIN QueryTable t'#13 +
                        'ON t.Query_No = c.Query_No'#13 +
                        'WHERE t.Query_Name = :QueryName';

    // Assign the item's text to the parameter to properly form
    // the WHERE clause so that we get only the data we want.
    sqTrans.ParamByName('QueryName').AsString := SearchVal;

    sqTrans.Open;
    try  
      while not sqTrans.Eof do
      begin
        // Populate ListBox2 with the matching rows we want
        ListBox2.Items.Add(sqTrans.FieldByName('Query_Items').AsString;
        sqTrans.Next;
      end;
    finally
      sqTrans.Close;
    end;
  finally
    // Reenable UI update for ListBox2 so newly added items are visible.
    ListBox2.Items.EndUpdate;
  end;
end;