全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:3022
推到 Plurk!
推到 Facebook!

ADOCommand支持unicode寬字符問題

尚未結案
jean2004
初階會員


發表:69
回覆:80
積分:39
註冊:2004-12-18

發送簡訊給我
#1 引用回覆 回覆 發表時間:2012-01-20 10:58:42 IP:112.224.xxx.xxx 訂閱
先轉貼一篇文章,下一樓說問題:

近日,在用delphi7unicode的程序時發現了這樣一個問題,就是使用TADOCommand組件執行sql語句時,如果sql語句中有unicode字符,存儲在數據庫裏會出現亂碼,使用TTntADOQuery也是一樣(使用參數方式不會出現亂碼,這裏只討論純sql的方式)。

procedure TADOCommand.AssignCommandText(const Value: WideString; Loading: Boolean); procedure InitParameters; var I: Integer; List: TParameters; NativeCommand: string; begin List := TParameters.Create(Self, TParameter); try NativeCommand := List.ParseSQL(Value, True); { Preserve existing values } List.AssignValues(Parameters); CommandObject.CommandText := NativeCommand; if not Loading and (Assigned(Connection) or (ConnectionString <> '')) then begin try SetConnectionFlag(cfParameters, True); try { Retrieve additional parameter info from the server if supported } Parameters.InternalRefresh; { Use additional parameter info from server to initialize our list } if Parameters.Count = List.Count then for I := 0 to List.Count - 1 do begin List[I].DataType := Parameters[I].DataType; List[I].Size := Parameters[I].Size; List[I].NumericScale := Parameters[I].NumericScale; List[I].Precision := Parameters[I].Precision; List[I].Direction := Parameters[I].Direction; List[I].Attributes := Parameters[I].Attributes; end finally SetConnectionFlag(cfParameters, False); end; except { Ignore error if server cannot provide parameter info } end; if List.Count > 0 then Parameters.Assign(List); end; finally List.Free; end; end; begin if (CommandType = cmdText) and (Value <> '') and ParamCheck then InitParameters else begin CommandObject.CommandText := Value; if not Loading then Parameters.Clear; end; end;

if (CommandType = cmdText) and (Value <> '') and ParamCheck then InitParameters 也就是當ParamChecktrue時,會執行InitParameters過程,我們看看這個InitParameters過程中發生了什麼: 首先它定義個一個變量:NativeCommand: string;,注意,是stirng不是widestring;我們接著往下看: NativeCommand := List.ParseSQL(Value, True); { Preserve existing values } List.AssignValues(Parameters); CommandObject.CommandText := NativeCommand; 在這裏,Valuewidestring類型的,而List.ParseSQL返回的是string類型的,同時NativeCommand也是string類型的,就這樣,一個好好的widestring的變量被放到了string類型的變量當中,然後又把NativeCommand賦給了CommandObject.CommandText,因此導致了CommandObject.CommandText並沒有得到應該賦給它的widesting值,這也就最終導致了存儲unicode時亂碼的發生。 解決方法也很簡單,(如果你不願意修改delphi源程序的話)只需要把ParamCheck置為false就可以了(delphi默認把ParamCheck置為true)。
<!--EndFragment-->
jean2004
初階會員


發表:69
回覆:80
積分:39
註冊:2004-12-18

發送簡訊給我
#2 引用回覆 回覆 發表時間:2012-01-20 11:00:10 IP:112.224.xxx.xxx 訂閱
問題
問題1D7中假設是因為上文作者所說的D7StringAnsiString的所以有問題,那麼XE2中的Stringunicode的,怎麼還有這個問題?
問題2、當使用參數時,如果SQL語句中也寫入unicode字符時,這時不能設置ParamCheckfalse,那麼該怎麼解決?
<!--EndFragment-->
系統時間:2024-04-27 9:28:53
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!