Delphi7.0中如何用代码访问数据的方法
一、第一种方法: 1、设计的界面如下:
2、主要代码:
(1)启动窗口中的主要代码:
Se:= ExtractFilePath(Application.ExeName) + 'data\jczk.mdb'; //动态取出
系统文件的路径 ADOADOQuery1.ConnectionString :='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+ Se+';Persist Security Info=False'; ADOADOQuery1.Close; ADOADOQuery1.SQL.Clear;
ADOADOQuery1.SQL.Add('select * from yhz');
ADOADOQuery1.Open;//ADOADOQuery1.ExecSQL;本句表示不返回值时的记录集合 ADOADOQuery1.Active:=true; (2)查询其它表时的代码: ADOADOQuery1.Close; ADOADOQuery1.SQL.Clear;
ADOADOQuery1.SQL.Add('select * from jf11'); ADOADOQuery1.Open; ADOADOQuery1.Active:=true;
(3)提示窗口:Application.MessageBox('ss','提示',64);
(4)说明:DataSource1必须要与ADOADOQuery1连接在一起;DBGrid1必须要与DataSource1连接在一起。
(5)取值:EDIT1.Text:=ADOADOQuery1.FieldByName('yhz04').AsString (6)怎么使用ADOQuery1给数据库添加数据? ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('insert into "Tab_Contron_record"'); ADOQuery1.SQL.Add('('+str_V+')');
ADOQuery1.SQL.Add('values('+str_T+')');
ADOQuery1.ParamByName('用户名').AsString:='admin';
1
ADOQuery1.ParamByName('连接设备IP').AsString:='192.168.18.66'; ADOQuery1.ParamByName('用户类型').AsString:='管理员';
ADOQuery1.ParamByName('连接时间').AsString:=datetimetostr(now); ADOQuery1.ParamByName('备注').AsString:='无';
ADOQuery1.ExecSQL; (7)、怎么样查询数据库中表的值,即条件查询(注意:Quotedstr()函数的使用):
cnn:='select * from sinfo where sid=200601001'; //“sid”字段为数值型可以直接使用; cnn:='select * from sinfo where sclass='+Quotedstr('高一一');//“sclass”字段为字符类型; //多条件进行查询的例子
cnn:='select * from sinfo where sclass='+Quotedstr('高一一')+' and ssex='+quotedstr('男');
ADOQuery1.Close ; ADOQuery1.SQL.Clear; ADOQuery1.SQL.Add(cnn); ADOQuery1.Open;
ADOQuery1.Active :=true;
(8)、与SQL Server2000远程数据库相连接的办法: //计算机进入界面的时候就可以进入,注意密码为“1”;数据库名称为“TEST”;IP地址为“127.0.0.1”,直接法:
cnstring:='Provider=SQLOLEDB.1;Password=1;Persist Security Info=True;User ID=sa;Initial Catalog=test;Data Source=127.0.0.1';
ADOQuery1.ConnectionString :=cnstring; 方框法:
//
计算机进入界面的时候就可以进入
cnstring:='Provider=SQLOLEDB.1;Pass
word='+Edit3.Text+';Persist Security Info=True;User ID=sa;Initial Catalog='+Edit2.Text+';Data Source='+Edit1.Text; //127.0.0.1'; ADOQuery1.ConnectionString :=cnstring;
(9)其它查询的例子和数据记录集的移动方法:
cnn:='select * from sinfo where sclass='+Quotedstr('高一一')+' and ssex='+quotedstr('男');
ADOQuery1.Close ; ADOQuery1.SQL.Clear; ADOQuery1.SQL.Add(cnn); ADOQuery1.Open;
ADOQuery1.Active :=true;
if ADOQuery1.RecordCount<>0 then begin
Application.MessageBox('您已经
查询到了相关的记录!','提示',64); ADOQuery1.Active :=true;
Edit1.Text:=ADOQuery1.FieldValues['sname'];//取出它的值 end else begin
2
Application.MessageBox('您设有查询到了相关的记录,点击退出!','提示',64); close; end;
ADOQuery1.Active :=true;
ADOQuery1.Next;//下一条记录
Edit1.Text:=ADOQuery1.FieldValues['sna