Rabu, 02 Juni 2010

Delphi: Connection To Mysql Using Ini Files

You may need a form that have uses iniFiles and also ADOConnection.
But you can change it with other connection component on Delphi.
Then add a Button, a Label to display status message, and some Edit to define the input variable, and then call this function.



procedure CreateConnection(host,database,username,password;string);
var
   FileIni : TIniFile;
   strConnection : string;
begin
  FileIni := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'conf.ini');

  if (host='') or (database='') or (username='') or (password='') then
  begin
     MessageDlg('some data is empty, please completed it !', mtError, [mbOK], 0);
     Exit;
  end;

  try
    ADOConnection.Close;
    labelStatus.Caption := 'Try To Connect To Database ' + i+ ' ON ' + '[' + host + ']';
    Screen.Cursor := crHourGlass;

    strConnection := 'Provider=MSDASQL.1;Password='+ password +
                    ';Persist Security Info=True;'+
                    'Extended Properties="DATABASE='+ database +
                    ';DRIVER={MySQL ODBC 3.51 Driver};'+
                    'OPTION=3;PWD=;PORT=3306;'+
                    'SERVER='+ host +
                    ';UID='+ username +' " ';

    ADOConnection.ConnectionString := strConnection;
    FileIni.WriteString('Connection', 'ConnectionString', strConnection);
    Application.ProcessMessages;
    ADOConnection.Open(username,password);
    FileIni.WriteString('Connection', 'UserName', username);
    FileIni.WriteString('Connection', 'Password', password);
    labelStatus.Caption := 'Connection Success';
    Screen.Cursor := crDefault;
  except
    labelStatus.Caption := 'Connect To Database Error' + database + ' ON ' + '[' + host + ']';
    MessageDlg('Connection Error (LOGIN FAILED)' + #13#10 + 'Please check again !', mtError,        [mbOK], 0);
    Screen.Cursor := crDefault;
  end;
  FileIni.Free;
end;

happy coding ;)

0 comments: