2013-03-04 121 views
0

我正在搜索如何將數據從列表視圖保存到數據庫的示例。從列表視圖插入數據到數據庫delphi

我有一些數據的列表視圖:

http://s24.postimage.org/i1rhxnadx/listview.jpg

和mysql數據庫:

ID,姓名,職務,自主學習,日期

有人能告訴我一個例子如何做這個?

thx。

+5

什麼是你試過嗎?你正在使用哪個數據庫組件? – RRUZ 2013-03-04 13:51:57

+0

我使用UniDac(devart.com)數據庫組件,我無法嘗試..因爲我無法填寫如何開始,你能給我一些提示嗎? – vkatsitadze 2013-03-04 14:06:15

回答

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; 
+0

感謝您的關注,稍後我會檢查並在發生一些變化後回報 – vkatsitadze 2013-03-04 16:53:26

+0

,我有工作來源。謝謝 – vkatsitadze 2013-03-07 15:07:38

1

以下解決方案使用TSQLQuery,這意味着我連接到火鳥。我相信還有其他的查詢組件會給你相同的結果。

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)