首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数据从列表视图插入到数据库delphi中

问将数据从列表视图插入到数据库delphi中
EN

Stack Overflow用户
提问于 2013-03-04 21:34:07
回答 2查看 2.4K关注 0票数 0

我正在寻找一个例子,如何将数据从listview保存到数据库中。

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

​

和数据库mysql:

ID,姓名,职位,日期

有没有人能给我举个这样做的例子?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-05 00:33:29

不知道TUNIQuery是否有ExecSql方法,但这将适用于TADOQuery,在我的例子中,ListView.ViewStyle被设置为vsReport,它包含4个cols。

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

代码语言:javascript
复制
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;
票数 1
EN

Stack Overflow用户

发布于 2013-03-05 17:23:58

下面的解决方案使用了一个TSQLQuery,这意味着我连接到了火鸟。我相信还有其他的查询组件会给你同样的结果。

代码语言:javascript
复制
 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;

查询本身应该是这样的

代码语言:javascript
复制
insert into table (name, position, sall, adate)
values (:p1, :p2, :p3, :p4)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15202777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档