一、在Delphi7中连接MS SQL Server 2000的方法。
刚开始时界面如下:添加4个控件。
设置控件属性过程:
1、ADOConnection1设置
1)双击ADOConnection1,进行设置连接字符串(作用是:选取连接驱动方式和连接的数据库设置)。过程如下图所示:
2、ADOQuery1设置:
1)ADOQuery1.connection属性为ADOConnection1;
2)ADOQuery1.SQL属性为select student.sno,sname,cname,grade from student,sc,course where student.sno=sc.sno and course.cno=sc.cno
3)ADOQuery1.Active设置为TRUE。
3、DataSource1设置
DataSet属性为ADOQuery1
4、DBGrid1设置
DataSource属性设置为DataSource1.
效果图:
二、通过Delphi7进行设计SQL查询的界面和程序实现。
1、界面设计
添加Edit,Button和Label控件,如图摆放和设置基本属性。
2、在BitBtn1的Click事件内完成程序。(Edit1和Edit2的综合查询,共4种情况)
procedure TForm1.BitBtn1Click(Sender: TObject); var i:integer; SqlStr:String; begin i:=0; if edit1.Text<>'' then i:=i+1; if edit2.Text<>'' then i:=i+2; case i of 0: begin SqlStr:='select student.sno,sname,cname,grade from student,sc,course ' +'where student.sno=sc.sno and course.cno=sc.cno '; adoquery1.Close; //关闭ADOQuery1,以便于进行SQL语句更新 adoquery1.SQL.Clear; //清空SQL语句 adoquery1.SQL.Add(sqlStr); //添加新的SQL adoquery1.Open; //新SQL有效 end; 1: begin SqlStr:='select student.sno,sname,cname,grade from student,sc,course ' +'where student.sno=sc.sno and course.cno=sc.cno and sname='''+edit1.Text+''''; adoquery1.Close; //关闭ADOQuery1,以便于进行SQL语句更新 adoquery1.SQL.Clear; //清空SQL语句 adoquery1.SQL.Add(sqlStr); //添加新的SQL adoquery1.Open; //新SQL有效 end; 2: begin SqlStr:='select student.sno,sname,cname,grade from student,sc,course ' +'where student.sno=sc.sno and course.cno=sc.cno and cname='''+edit2.Text+''''; adoquery1.Close; //关闭ADOQuery1,以便于进行SQL语句更新 adoquery1.SQL.Clear; //清空SQL语句 adoquery1.SQL.Add(sqlStr); //添加新的SQL adoquery1.Open; //新SQL有效 end; 3: begin SqlStr:='select student.sno,sname,cname,grade from student,sc,course ' +'where student.sno=sc.sno and course.cno=sc.cno and sname='''+edit1.Text+'''' +' and cname='''+edit2.Text+''''; adoquery1.Close; //关闭ADOQuery1,以便于进行SQL语句更新 adoquery1.SQL.Clear; //清空SQL语句 adoquery1.SQL.Add(sqlStr); //添加新的SQL adoquery1.Open; //新SQL有效 end; end; end;
3、在Edit2的change事件内写模糊查询。代码如下(Edit1的类似):
procedure TForm1.Edit2Change(Sender: TObject); var SqlStr:String; begin SqlStr:='select student.sno,sname,cname,grade from student,sc,course ' +'where student.sno=sc.sno and course.cno=sc.cno and cname like ''%'+edit2.Text+'%'''; adoquery1.Close; //关闭ADOQuery1,以便于进行SQL语句更新 adoquery1.SQL.Clear; //清空SQL语句 adoquery1.SQL.Add(sqlStr); //添加新的SQL adoquery1.Open; //新SQL有效 end;