【问题标题】:insert data from listview into database delphi将列表视图中的数据插入数据库delphi
【发布时间】:2013-03-04 13:34:07
【问题描述】:

我正在搜索如何将列表视图中的数据保存到数据库中的示例。

我有一个包含一些数据的列表视图:

和数据库mysql:

ID、姓名、职位、销售、日期

有人可以给我举个例子吗?

谢谢。

【问题讨论】:

  • 你尝试了什么?您使用的是哪些数据库组件?
  • 我正在使用 UniDac(devart.com) db 组件,我无法尝试.. 因为我无法填写如何启动,您能给我一些提示吗?

标签: delphi delphi-xe delphi-xe3


【解决方案1】:

不知道 TUNIQuery 是否有 ExecSql 方法,但这将适用于 TADOQuery,在我的情况下,ListView.ViewStyle 设置为 vsReport,它包含 4 个列。

我认为如果你使用 StringGrid 或 Dbgrid 会更容易处理

procedure TForm1.PostData;
const
  SQLCMD = 'INSERT INTO MYTABLE (NAME, POSITION, SALL, DATE) VALUES '+
  '(%s, %s, %s, %s)';
var
//  IL: TListItem;
  I, J, ItemsCount, SubItemsCount: integer;
  LineItem: array of string;
begin

  ItemsCount:= ListView1.Items.Count;
  for I := 0 to ItemsCount - 1 do // looping thru the items
  begin
    SubItemsCount:= ListView1.Items[I].SubItems.count;
    SetLength(LineItem, SubItemsCount + 1);
    LineItem[0]:= ListView1.Items[0].Caption; // the first item caption (first col)
    for J := 0 to SubItemsCount - 1 do   // looping thru the subitems of each line
      LineItem[J+1]:= ListView1.Items[I].SubItems.Strings[J];
//
//  just to see the sql command
//    ShowMessage(
//    Format(SQLCMD, [ QuotedStr(LineItem[0]),
//                     QuotedStr(LineItem[1]),
//                     LineItem[2], //int field no need to quote the parameter
//                     QuotedStr(LineItem[3])]
//    ));

//
    with TAdoQuery.Create(nil) do
    try
      ConnectionString:= 'Your Connection String';
      SQL.Text:=
      Format(SQLCMD, [QuotedStr(LineItem[0]),
                      QuotedStr(LineItem[1]),
                      LineItem[2], //int field no need to quote the parameter
                      QuotedStr(LineItem[3]));
      ExecSql; // you might handel execsql to know the row was affected, also not sure if unidac have the same method
    finally
      Free;
    end;

    SetLength(LineItem, 0);

  end;
end;

【讨论】:

  • 感谢您的关注,我稍后会检查并反馈报告
【解决方案2】:

以下解决方案使用 TSQLQuery,这意味着我正在连接到 Firebird。我确信还有其他查询组件会为您提供相同的结果。

 with dstlist do  // this is the list view
  for i:= 1 to items.count do
   with qInsert do   // this is the query component
    begin
     dstlist.itemindex:= i - 1;
     lvitem:= dstlist.selected;   // select the correct node
     close;
     parambyname ('p1').asstring:= lvitem.caption;  // name
     parambyname ('p2').asstring:= lvitem.subitems[0];  // position
     parambyname ('p3').asinteger:= strtoint (lvitem.subitems[1]);  // sall
     parambyname ('p4').asdate:= strtodate (lvitem.subitems[2]);
     execsql;
    end;

查询本身类似于

insert into table (name, position, sall, adate)
values (:p1, :p2, :p3, :p4)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多