One of the most attractive features of delphi is its powerful database access capability, which can easily create and edit databases through the database desktop tool. Due to practical reasons, we often need to dynamically establish a certain database while the program is running.
If you ask users to manually create data tables using the database desktop tool, the program you write will be greatly discounted, but you don’t have to worry that delphi can complete this function in language, which provides us with convenience. I have summarized two methods in my study and practice, which I call the table method and the sql method. The following describes the process of dynamic database establishment through simple examples.
1. Table method:
1. (Take the example of establishing a paradox data table assuming the library name is ljh.db). Create a new project file zhoudf.dPR. Add db and dbtables units to the uses statement in unit1.
2. Select the button element on the panel and place it in the form1 table. Double-click button1 to enter the following code.
Procedure Tform1.Button2Click(Sender: Tobject);
var table1:ttable; begin table1:=ttable.create(self);
with table1 do begin active:=false;
tablename:='ljh.db';
tabletype:=ttparadox; with fieldsdefs do {This method adds fields to ljh.db} begin clear;
add('yj',ftdate,0,false);
add('zp', ftstring,10,false); {Add specific field name and type}
add('zdm',ftinteger,0,false);
end;
With indexdefs do {This method adds index field to ljh.db} Begin Clear;
Add('yjindex','yj',[ixprimary]);
end;
createtable;
end;
end;
2. SQL method: Select the button element on the panel and place it in the form1 table. Double-click button2 to enter the following code.
Procedure Tform1.Button2Click(Sender: Tobject);
var table2:tquery; begin table2:=tquery.create(self);
with table2 do begin with sql do begin clear;
add('create table "ljh.db"');
add('(yj date,'); {note the '('} in the quotes
add('zp char(10),');
add('zdm int)'); {note ')' in quotes}
end;
execsql;
sql.clear;
sql.add('create index yj on "ljh.db" (yj)'); {This sql statement adds index field to ljh.db}
execsql;
end;
end;
* Just compile this program. * It should be noted that if the library is already there, an error message will be generated, and if the library is already there, the table method is not required to be considered.