Im writing a database application, using Delphi and need to import data on a excel sheet and save it in a access database. I have no idea how to do this, what components to use, or if it is even possible, can you please help me.
You have several options, try one of these
1) using the DoCmd.TransferSpreadsheet function , this method is simpler but not very flexible.
{$APPTYPE CONSOLE}
{$R *.res}
uses
SysUtils,
ActiveX,
ComObj;
procedure ImportDataAccess(const AccessDb, TableName, ExcelFileName:String);
Const
acQuitSaveAll = $00000001;
acImport = $00000000;
acSpreadsheetTypeExcel9 = $00000008;
acSpreadsheetTypeExcel12 = $00000009;
var
LAccess : OleVariant;
begin
//create the COM Object
LAccess := CreateOleObject('Access.Application');
//open the access database
LAccess.OpenCurrentDatabase(AccessDb);//if the access database doesn't exist use the NewCurrentDatabase method instead.
//import the data
LAccess.DoCmd.TransferSpreadsheet( acImport, acSpreadsheetTypeExcel9, TableName, ExcelFileName, True);
LAccess.CloseCurrentDatabase;
LAccess.Quit(1);
end;
begin
try
CoInitialize(nil);
try
ImportDataAccess('C:\Data\Database1.accdb','Sales','C:\Data\Sales.xlsx');
Writeln('Done');
finally
CoUninitialize;
end;
except
on E:EOleException do
Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
2) using the ado components, a more flexible way.
{$APPTYPE CONSOLE}
{$R *.res}
uses
Data.DB,
Data.Win.ADODB,
SysUtils,
ActiveX,
ComObj;
procedure ImportDataADO(const AccessDb, TableName, ExcelFileName:String);
var
LAdoQueryExcel : TADOQuery;
LADOAccesCmd : TADOCommand;
begin
LAdoQueryExcel:=TADOQuery.Create(nil);
LADOAccesCmd:=TADOCommand.Create(nil);
try
//set the connection string for access
LADOAccesCmd.ConnectionString:=Format('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=%s;',[AccessDb]);
LADOAccesCmd.Parameters.Clear;
LADOAccesCmd.CommandText:='INSERT INTO Sales (id,name) VALUES (:id,:name)';
LADOAccesCmd.ParamCheck:=False;
//set the connection string for excel
LAdoQueryExcel.ConnectionString:=Format('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=%s;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1"',[ExcelFileName]);
LAdoQueryExcel.SQL.Add('SELECT * FROM [Sheet1$]');
LAdoQueryExcel.Open;
while not LAdoQueryExcel.eof do
begin
LADOAccesCmd.Parameters.ParamByName('id').Value := LAdoQueryExcel.FieldByname('id').AsInteger;
LADOAccesCmd.Parameters.ParamByName('name').Value := LAdoQueryExcel.FieldByname('name').AsString;
LADOAccesCmd.Execute;
LAdoQueryExcel.Next;
end;
finally
LAdoQueryExcel.Free;
LADOAccesCmd.Free;
end;
end;
begin
try
CoInitialize(nil);
try
ImportDataADO('C:\Datos\Database1.accdb','Sales','C:\Datos\Sales.xlsx');
Writeln('Done');
finally
CoUninitialize;
end;
except
on E:EOleException do
Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
Related
Am trying to store my TTreeView inside SQL Server database table by using the next procedure:
procedure Save;
var
BlobField :TBlobField;
Query:TADOQuery;
Stream:TStream;
begin
Stream := TMemoryStream.Create;
Query := TADOQuery.Create(Self);
Query.SQL.Add('Select * From MyTable') ;
Query.Active := True;
Query.First;
Query.Edit;
BlobField := Query.FieldByName('MyTableField') as TBlobField;
Stream := Query.CreateBlobStream(BlobField, bmWrite);
TreeView1.SaveToStream(Stream);
Query.Refresh;
Query.Free;
Stream.Free;
end;
But every time I am getting the error: DataSet is not in edit or insert mode.
I'm using Delphi 10.1, Win 10, SQL server 2019.
Change Query.Refresh; to Query.Post;
Also, you need to Free the blob stream to finalize writing to the blob field before you then Post to commit the new data into the DB.
Also, you are leaking an unused TMemoryStream object.
Try this:
procedure Save;
var
BlobField: TField;
Query: TADOQuery;
Stream: TStream;
begin
Query := TADOQuery.Create(nil);
try
Query.SQL.Text := 'Select TOP(1) * From MyTable';
Query.Open;
try
Query.First;
Query.Edit;
try
BlobField := Query.FieldByName('MyTableField');
Stream := Query.CreateBlobStream(BlobField, bmWrite);
try
TreeView1.SaveToStream(Stream);
finally
Stream.Free;
end;
Query.Post;
except
Query.Cancel;
raise;
end;
finally
Query.Close;
end;
finally
Query.Free;
end;
end;
I'm looking for informations on how to put TRichEdit into an Array and save it to Local file (ex: File.dat).
The goal is to store a number of text, with a description, and the 'name' of it.
I think I have to start with:
type
TMessage = record
Name : string;
Desc : string;
Text : TMemoryStream;
end;
var ARListMessages: array[1..50] of TMessage
And add data with something like:
richedit.Lines.SaveToStream( ARListMessages[i].Text );
How to create the Array, and make manipulations on it (Add, remove
...) with the 'name'?
How can I save it (Array), and load it easily from local storage ? (Ex:
File.dat)
I've found some informations here, without beeing able to make something working.
Thanks for your time.
[EDIT 18/09/2017]
I'm Still looking to find a solution, and try to find a way to save my informations to a local file.
My actual code to test is :
var
MessageArray : array of TMessage;
// // // //
SetLength(MessageArray, 1);
MessageArray[0].Name := 'Hey You';
MessageArray[0].Desc := 'Im here and will stay here, just in case';
MessageArray[0].Text := TMemoryStream.Create;
MessageArray[0].Text.Position := 0;
RichEdit1.plaintext := false;
RichEdit1.Lines.SaveToStream( MessageArray[0].Text );
So, looking to save MessageArray, but haven't find how to do that yet.
I've take a look on SuperObjet, but can't find how to deal with it.
Omxl was looking Great and easy, but free trial ... :(
I've been able to have an answer.
I share it here if someone need the solution.
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Generics.Collections, Classes, System.Zip;
type
TPersonne = class
strict private
FNom : string;
FPrenom: string;
public
property Nom: string read FNom write FNom;
property Prenom: string read FPrenom write FPrenom;
end;
TFamille = class(TDictionary<string, TPersonne>)
private
procedure LoadFromStream(stream: TStream);
procedure SaveToStream(stream: TStream);
public
procedure LoadFromFile(const AFileName: string);
procedure SaveToFile(const AFileName: string);
end;
procedure TFamille.SaveToStream(stream: TStream);
var
i: Integer;
Personne: TPersonne;
Pair: System.Generics.Collections.TPair<string, TPersonne>;
Writer: TWriter;
begin
Writer := TWriter.Create(stream, 4096);
try
Writer.WriteListBegin;
for Pair in Self do
begin
Writer.WriteString(Pair.Key);
Writer.WriteListBegin;
Personne := Pair.Value;
Writer.WriteString(Personne.Nom);
Writer.WriteString(Personne.Prenom);
Writer.WriteListEnd;
end;
Writer.WriteListEnd;
finally
Writer.Free;
end;
end;
procedure TFamille.LoadFromStream(stream: TStream);
var
Personne: TPersonne;
Reader: TReader;
sKey: string;
begin
Clear;
Reader := TReader.Create(stream, 1024);
try
Reader.ReadListBegin;
while not Reader.EndOfList do
begin
sKey := Reader.ReadString;
Personne := TPersonne.Create;
Reader.ReadListBegin;
while not Reader.EndOfList do
begin
Personne.Nom := Reader.ReadString;
Personne.Prenom := Reader.ReadString;
end;
Reader.ReadListEnd;
Add(sKey, Personne);
end;
Reader.ReadListEnd;
finally
Reader.Free;
end;
end;
procedure TFamille.LoadFromFile(const AFileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(AFileName, fmOpenRead);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TFamille.SaveToFile(const AFileName: string);
var
stream: TStream;
begin
stream := TFileStream.Create(AFileName, fmCreate);
try
SaveToStream(stream);
finally
stream.Free;
end;
end;
var
Famille: TFamille;
Personne: TPersonne;
begin
try
Famille := TFamille.Create;
try
Personne := TPersonne.Create;
Personne.Nom := 'Julie';
Personne.Prenom := 'Albertine';
Famille.Add('1', Personne);
Famille.SaveToFile('D:\famille.txt');
finally
FreeAndNil(Famille);
end;
Famille := TFamille.Create;
try
Famille.LoadFromFile('D:\famille.txt');
if Famille.Count > 0 then
Writeln(Famille['1'].Nom + ' ' + Famille['1'].Prenom);
finally
FreeAndNil(Famille);
end;
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Thanks all for your Help !
How to create the Array, and make manipulations on it (Add, remove
...) with the 'name'?
From your first code the array is already created. No further work is needed. And even if you use dynamic arrays you still don't have to do any thing just declaring it will suffice.
If you are asking "How to create the array ?" as in "How to create such a list, so I could add, remove with the 'name' field" then I would suggest TDictionary (instead of the city names use your field 'name' as a key) to do the manipulations and then when saving use this
How can I save it (Array), and load it easily from local storage ?
(Ex: File.dat)
You can't directly just like array.savetofile;.You need to use one of file handling methods like TFileStream to store the array.
Note: in your edit the memory stream will cause you only trouble because each time you create it you will need to free it after its use instead use these functions to extract formatted text and change the field Text : TMemoryStream; to Text : string;
RichTextToStr: Convert the rich format text to a string.
function RichTextToStr(RichEdit:TRichEdit):string;
var
SS : TStringStream;
begin
SS := TStringStream.Create('');
try
RichEdit.Lines.SaveToStream(SS);
Result := SS.DataString;
finally
SS.Free;
end;
end;
loadToRichedit: Load the formatted text to the RichEdit again.
procedure loadToRichedit(Const St:string;RichEdit:TRichEdit);
var
SS : TStringStream;
begin
SS := TStringStream.Create(St);
try
RichEdit.Lines.LoadFromStream(SS);
finally
SS.Free;
end;
end;
I would just like a tip about a situation.
I created a Windows service that does the task management of my application.
The service connect to the database (Firebird) and call a component that does the task management.
The process works fine, however, in Windows 10 the service does not start automatically after the computer is restarted. In other versions of Windows everything works perfectly. In testing, I have identified that if I comment on the method that calls the execution of the tasks, the service usually starts on Windows 10.
Procedure TDmTaskService.ServiceExecute(Sender: TService);
Begin
Inherited;
While Not Terminated Do
Begin
//Process;
Sleep(3000);
ServiceThread.ProcessRequests(False);
End;
End;
The problem is that nothing exception is generated in component or service.
By analyzing the Windows Event Monitor, I have identified that the error that occurred with my service is Timeout, in which case the service was unable to connect to the service manager within the time limit. No more exceptions are generated.
Would anyone have any about Windows Services made in Delphi that connect to database?
Example of my source code:
**Base class:**
unit UnTaskServiceDmBase;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs;
type
TDmTaskServicosBase = class(TService)
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
DmTaskServiceBase: TDmTaskServicosBase;
implementation
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
DmJBServicosBase.Controller(CtrlCode);
end;
function TDmTaskServicosBase.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
end.
**Service Class:**
Unit UnTaskServiceDm;
Interface
Uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,
UnJBTask,
UnJBReturnTypes,
UnJBUtilsFilesLog,
UnTaskServiceDmConfig,
UnTaskServiceDmConnection,
ExtCtrls,
IniFiles;
Type
TDmTaskService = Class(TDmTaskServicosBase)
Procedure ServiceExecute(Sender: TService);
Procedure ServiceCreate(Sender: TObject);
Procedure ServiceStop(Sender: TService; Var Stopped: Boolean);
Private
FTaskServiceConfig: TDmTaskServiceConfig;
FStatus: TResultStatus;
FDmConnection: TDmTaskServiceConnection;
FJBTask: TJBTask;
FLog: TJBUtilsFilesLog;
Procedure ExecuteTasksSchedule;
Procedure UpdateServiceInformation;
Procedure Process;
Procedure UpdateConnection;
Public
Function GetServiceController: TServiceController; Override;
End;
Implementation
{$R *.DFM}
Procedure ServiceController(CtrlCode: DWord); Stdcall;
Begin
DmTaskService.Controller(CtrlCode);
End;
Procedure TDmTaskService.UpdateConnection;
Begin
Try
FDmConnection.SqcCon.Connected := False;
FDmConnection.SqcCon.Connected := True;
FLog.Adicionar('Conexão com banco restabelecida.');
FLog.FinalizarLog;
Except
On E: Exception Do
Begin
FLog.Adicionar('Erro ao restabelecer conexão com o banco de dados.' +
sLineBreak + sLineBreak + E.Message);
FLog.FinalizarLog;
End;
End;
End;
Procedure TDmTaskService.UpdateServiceInformation;
Begin
Inherited;
Try
Try
FTaskServiceConfig.Load;
FLog.Adicionar('Dados registro serviço.');
FLog.Adicionar('Nome: ' + FTaskServiceConfig.ServiceName);
FLog.Adicionar('Descrição: ' + FTaskServiceConfig.ServiceDescription);
If (FTaskServiceConfig.ServiceName <> EmptyStr) And
(FTaskServiceConfig.ServiceDescription <> EmptyStr) Then
Begin
Name := FTaskServiceConfig.ServiceName ;
DisplayName := FTaskServiceConfig.ServiceDescription;
End;
FTaskServiceConfig.Close;
Except
On E: Exception Do
Begin
FLog.Adicionar('Erro adicionar dados registro serviço.');
FLog.Adicionar('Erro ocorrido: ' + sLineBreak + sLineBreak + E.Message);
End;
End;
Finally
FLog.Adicionar('Name: ' + Name);
FLog.Adicionar('DisplayName: ' + DisplayName);
FLog.FinalizarLog;
End;
End;
Procedure TDmTaskService.Process;
Begin
Try
If FDmConnection.SqcCon.Connected Then
Begin
ExecuteTasksSchedule;
End
Else
UpdateConnection;
Except
On E: Exception Do
Begin
FLog.Adicionar('Ocorreu um erro ao checar as tarefas.' + sLineBreak +
'Erro ocorrido: ' + sLineBreak + E.Message);
FLog.FinalizarLog;
UpdateConnection;
End;
End;
End;
Procedure TDmTaskService.ExecutarTarefasAgendadas;
Begin
If FJBTask.ExistTaskDelayed Then
Begin
Try
FJBTask.ExecuteTasks;
Except
On E: Exception Do
Begin
FLog.Adicionar('Ocorreu um erro ao executar as tarefas agendadas.' +
sLineBreak + 'Erro ocorrido: ' + sLineBreak + E.Message);
FLog.FinalizarLog;
UpdateConnection;
End;
End;
End;
End;
Function TDmTaskService.GetServiceController: TServiceController;
Begin
Result := ServiceController;
End;
Procedure TDmTaskService.ServiceCreate(Sender: TObject);
Begin
Inherited;
Try
FLog := TJBUtilsFilesLog.Create;
FLog.ArquivoLog := IncludeTrailingPathDelimiter(FLog.LogFolder) + 'TaksService.log';
FDmConnection := TDmTaskServiceConexao.Create(Self);
FDmConnection.Log := FLog;
FJBTask := TJBTarefa.Create(Self);
FJBTask.SQLConnection := FDmConnection.SqcConexao;
FTaskServiceConfig := TDmTaskServiceConfig.Create(Self);
FTaskServiceConfig.SQLConnection := FDmConnection.SqcConexao;
FStatus := FDmConnection.ConfigurouConexao;
If FStatus.ResultValue Then
Begin
UpdateServiceInformation;
End
Else
Begin
FLog.Adicionar(FStatus.MessageOut);
FLog.FinalizarLog;
End;
Except
On E: Exception Do
Begin
FLog.Adicionar('Não foi possível iniciar o serviço.' + sLineBreak +
'Erro ocorrido: ' + sLineBreak + sLineBreak + E.Message);
FLog.FinalizarLog;
Abort;
End;
End;
End;
Procedure TDmTaskService.ServiceExecute(Sender: TService);
Begin
Inherited;
While Not Terminated Do
Begin
Process;
Sleep(3000);
ServiceThread.ProcessRequests(False);
End;
End;
Procedure TDmTaskService.ServiceStop(Sender: TService; Var Stopped: Boolean);
Begin
Inherited;
If Assigned(FDmConnection) Then
Begin
FLog.Adicionar('Finalizando serviço.');
FLog.Adicionar('Fechando conexão.');
Try
FDmConnection.SqcConexao.Close;
Finally
FLog.FinalizarLog;
End;
End;
End;
End.
By analyzing the Windows Event Monitor, I have identified that the error that occurred with my service is Timeout, in which case the service was unable to connect to the service manager within the time limit. No more exceptions are generated.
Do not connect to your database, or do any other lengthy operations, in the TService.OnCreate event. Such logic belongs in the TService.OnStart event instead. Or better, create a worker thread for it, and then start that thread in the TService.OnStart event and terminate it in the TService.On(Stop|Shutdown) events.
When the SCM starts your service process, it waits for only a short period of time for the new process to call StartServiceCtrlDispatcher(), which connects the process to the SCM so it can start receiving service requests. StartServiceCtrlDispatcher() is called by TServiceApplication.Run() after all TService objects have been fully constructed first. Since the OnCreate event is called while your process is trying to initialize itself, before StartServiceCtrlDispatcher() is called, any delay in service construction can cause the SCM to timeout and kill the process.
Also, you should get rid of your TService.OnExecute event handler completely. You shouldn't even be using that event at all, and what you currently have in it is no better than what TService already does internally when OnExecute is not assigned any handler.
In your service code :
- you can try to add Dependencies on your Firebird Service
- you can increase WaitHint
if it still not work : you can start as automatic but "Delayed"
I found it otherwise to solve, however, I thank everyone for the tips, because in a timely manner you will make improvements to my service.
The solution was to extend the service startup timeout through the Windows ServicesPipeTimeout registry key.
For my case it worked perfectly.
I increased the value of ServicesPipeTimeout to 120000 (2 minutes).
By default the value is 30000 (30 seconds) or less.
To manual Edit:
1) Open the Windows Regedit App;
2) Locate and then click the following registry subkey:
- HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control
In the panel values, locate the ServicesPipeTimeout entry.
** Note **:
If the ServicesPipeTimeout entry does not exist, you must create it. To do
this, follow these steps:
- On the Edit menu, point to New, and then click DWORD Value.
- Type ServicesPipeTimeout, and then press ENTER.
3) Right-click ServicesPipeTimeout, and then click Modify.
4) Click Decimal, type 120000, and then click OK.
** 120000 miliseconds = 2 minutes
5) Restart the computer.
In Delphi (Sample registry value):
Procedure TForm3.JBButton3Click(Sender: TObject);
Const
CKeyConfigTimeout = 'SYSTEM\CurrentControlSet\Control';
CValueConfigTimeout = 'ServicesPipeTimeout';
Var
LReg: TRegistry;
Begin
LReg := TRegistry.Create;
Try
LReg.RootKey := HKEY_LOCAL_MACHINE;
LReg.OpenKey(CKeyConfigTimeout, False);
LReg.WriteInteger(CValueConfigTimeout, 120000);
Finally
LReg.CloseKey;
FreeAndNil(LReg);
End;
End;
Note: The delphi application with the registry update code needs to run in administrator mode for Windows Vista / Server or Superior versions;
I want to retrieve the SQL Server Protocols Network Configuration.
I tried searching for a windows registry or any config file related to this, but the only sample which I found is for powershell Enable or Disable a Server Network Protocol (SQL Server PowerShell), and uses .Net classes.
So the question is : How can retrieve the SQL Server Protocols Network Configuration using delphi?
You can use the ServerNetworkProtocol WMI class and also connect to the correct namespace depending of the SQL Server Version.
SQL Server 2005 = ComputerManagement
SQL Server 2008 = ComputerManagement10
SQL Server 2012 = ComputerManagement11
Try this sample
{$APPTYPE CONSOLE}
uses
SysUtils,
ActiveX,
ComObj,
Variants;
type
TMSSQlServerType=(MSSQL2005, MSSQL2008, MSSQL2012);
procedure GetServerNetworkProtocolInfo(SQlServerType: TMSSQlServerType; const InstanceName: string);
const
WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
wbemFlagForwardOnly = $00000020;
MSSQLNameSpaces : array [TMSSQlServerType] of string = ('ComputerManagement','ComputerManagement10','ComputerManagement11');
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
begin;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, Format('root\Microsoft\SqlServer\%s',[MSSQLNameSpaces[SQlServerType]]), WbemUser, WbemPassword);
FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM ServerNetworkProtocol Where InstanceName="%s"', [InstanceName]),'WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
Writeln(Format('Enabled %s',[String(FWbemObject.Enabled)]));// Boolean
Writeln(Format('MultiIpConfigurationSupport %s',[String(FWbemObject.MultiIpConfigurationSupport)]));// Boolean
Writeln(Format('ProtocolDisplayName %s',[String(FWbemObject.ProtocolDisplayName)]));// String
Writeln(Format('ProtocolName %s',[String(FWbemObject.ProtocolName)]));// String
Writeln;
FWbemObject:=Unassigned;
end;
end;
begin
try
CoInitialize(nil);
try
GetServerNetworkProtocolInfo(MSSQL2008,'MSSQLSERVER');
finally
CoUninitialize;
end;
except
on E:EOleException do
Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
I'm having trouble inserting Unicode into a SQL Server database using Delphi ZeosLib and Delphi 7, and then reading the inserted value. I've created a simple test program that first inserts and then queries the inserted value.
The test table schema:
CREATE TABLE [dbo].[incominglog](
[message] [nvarchar](500) NULL
) ON [PRIMARY]
I've upload the simple test program source (ZeosLib source included) - click here to download. I've also included ntwdblib.dll but you can use your own.
The test program also requires TNT component which can be downloaded from here
Using the test program, the Unicode characters that I have inserted appear as question marks on retrieval - I'm not certain whether the problem lies with the insert code or the query code.
I've also tried encoding the data into utf-8 before inserting and then decoding the data after retrieving from utf-8 - please search "//inserted as utf8" in the test program source. I'm able to view the Unicode after it has been decoded, so this method works. However, for my actual application, I can't encode as UTF-8 as SQL Server doesn't support UTF-8 completely - some characters can't be stored. See my previous question here.
Will appreciate any pointers. :)
Meanwhile, here's the source for the Test program:
unit Unit1;
interface
uses
ZConnection, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ZAbstractRODataset, ZAbstractDataset, ZAbstractTable, ZDataset,
StdCtrls, TntStdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
TntMemo1: TTntMemo;
Button2: TButton;
TntEdit1: TTntEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
FZConnection: TZConnection;
FZQuery: TZQuery;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
tntmemo1.Lines.Clear;
FZConnection := TZConnection.Create(Owner);
FZConnection.LoginPrompt := False;
FZQuery := TZQuery.Create(Owner);
FZQuery.Connection := FZConnection;
FZConnection.Protocol := 'mssql';
FZConnection.Database := 'replace-with-your-db';
FZConnection.HostName := 'localhost';
FZConnection.User := 'sa';
FZConnection.Password := 'replace-with-your-password';
FZConnection.Connect;
FZQuery.SQL.Text := 'SELECT * from incominglog';
FZQuery.ExecSQL;
FZQuery.Open;
FZQuery.First;
while not FZQuery.EOF do
begin
tntmemo1.Lines.add(FZQuery.FieldByName('message').AsString);
// tntmemo1.Lines.add(utf8decode(FZQuery.FieldByName('message').AsString)); //inserted as utf8
FZQuery.Next;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
sqlstring, data:widestring;
begin
FZConnection := TZConnection.Create(Owner);
FZConnection.LoginPrompt := False;
FZQuery := TZQuery.Create(Owner);
FZQuery.Connection := FZConnection;
FZConnection.Protocol := 'mssql';
FZConnection.Database := 'replace-with-your-db';
FZConnection.HostName := 'localhost';
FZConnection.User := 'sa';
FZConnection.Password := 'replace-with-your-password';
FZConnection.Connect;
data:= tntedit1.Text;
// data:= utf8encode(tntedit1.Text); //inserted as utf8
sqlstring:= 'INSERT INTO INCOMINGLOG ([MESSAGE]) VALUES(N''' + data + ''')';
FZQuery.SQL.Text := sqlstring;
FZQuery.ExecSQL;
end;
end.
I have not tested your example, but I'm able to save and retrieve from database Unicode characters without problem on SQL Server with Delphi 7 VCL/CLX and zeoslib.
I think in your case it will be enough changing your save procedure like this :
procedure TForm1.Button2Click(Sender: TObject);
var
sqlstring : widestring;
data : UTF8String;
begin
FZConnection := TZConnection.Create(Owner);
FZConnection.LoginPrompt := False;
FZQuery := TZQuery.Create(Owner);
FZQuery.Connection := FZConnection;
FZConnection.Protocol := 'mssql';
FZConnection.Database := 'replace-with-your-db';
FZConnection.HostName := 'localhost';
FZConnection.User := 'sa';
FZConnection.Password := 'replace-with-your-password';
FZConnection.Connect;
data:= UTF8String( utf8encode(tntedit1.Text) );
sqlstring:= 'INSERT INTO INCOMINGLOG ([MESSAGE]) VALUES(:DATA)';
FZQuery.SQL.Text := sqlstring;
FZQuery.ParamByName('DATA').AsString := data;
FZQuery.ExecSQL;
end;
The point is changing your data string variable in UTF8String type, and use parameters pass the data string to the query ...
To be honest I use it with a ZTable and Post command, but it should be the same with a ZQuery like yours ...