Alex Rivera | Logout

Delphi 7: ADO, need basic coding example

Asked 2010-05-27T01:56:46.193
11

I am a complete beginner here. Can someone please post some Delphi code to

  • create a database
  • add a simple table
  • close the database

then, later

  • open a database
  • read each table
  • read each field of a given table
  • perform a simple search

Sorry to be so clueless. I did google, but didn't find a useful tutorial ...

In addition, it would be useful if the underlying database were MySql (5.1.36) (I don't even know if that makes any difference)

Edit
Report

2 Answers

26

@mawg, i wrote an simple program for you to ilustrate how work with ADO and Delphi. this is an console application, but explains the basics.

before you execute this code you must download and install the odbc connector from this location.

You can improve and adapt this code to your requirements.

program ProjectMysqlADO;

{$APPTYPE CONSOLE}

uses
  ActiveX,
  DB,
  ADODB,
  SysUtils;

const
//the connection string
StrConnection='Driver={MySQL ODBC 3.51 Driver};Server=%s;Database=%s;User=%s; Password=%s;Option=3;';


var
AdoConnection : TADOConnection;

procedure SetupConnection(DataBase:String);//Open a connection
begin
  Writeln('Connecting to MySQL');
  AdoConnection:=TADOConnection.Create(nil);
  AdoConnection.LoginPrompt:=False;//dont ask for the login parameters
  AdoConnection.ConnectionString:=Format(StrConnection,['your_server',DataBase,'your_user','your_password']);
  AdoConnection.Connected:=True; //open the connection
  Writeln('Connected');
end;

procedure CloseConnection;//Close an open connection
begin
  Writeln('Closing connection to MySQL');
  if AdoConnection.Connected then
  AdoConnection.Close;
  AdoConnection.Free;
  Writeln('Connection closed');
end;

procedure CreateDatabase(Database:string);
begin
  Writeln('Creating Database '+database);
  AdoConnection.Execute('CREATE DATABASE IF NOT EXISTS '+Database,cmdText);
  Writeln('Database '+database+' created');
end;

procedure CreateTables;
begin
  Writeln('Creating Tables');
  AdoConnection.Execute(
  'CREATE TABLE IF NOT EXISTS customers ('+
  'id      INT,'+
  'name    VARCHAR(100),'+
  'country VARCHAR(25) )',cmdText);
  Writeln('Tables Created');
end;


procedure DeleteData;
begin
  Writeln('Deleting dummy data');
  AdoConnection.Execute('DELETE FROM customers');
  Writeln('Data deleted');
end;

procedure InsertData;

    Procedure InsertReg(id:integer;name,country:string);
answered 2010-05-27T06:02:07.840
4

One of the best places for Delphi examples is www.delphi.about.com. They have heaps of tutorials and examples. Their forums are really good as well. Dave

answered 2010-05-27T02:06:52.050

Your Answer