我写了最简单的程序,连接到acceessdb,从Memo列我可以执行SQL查询。
示例查询:
SELECT
company_name, date_of_order_start, date_of_order_finish
FROM
customers
INNER JOIN
orders ON customers.id_customer = orders.id_customer
WHERE
company_name='Ампер';
它工作正常,但这个查询
SELECT
company_name, date_of_order_start, date_of_order_finish, amount
FROM
customers
INNER JOIN
orders ON customers.id_customer = orders.id_customer
INNER JOIN
invoice ON invoice.id_order = orders.id_order
WHERE
company_name='Ампер';
返回语法错误
表达式中缺少运算符&customers; cid.customer = orders.id_customer INNER JOIN发票上发票.id_order = orders.id_orde' 。
是的,r
中的最终.id_order
无法显示。
请帮助,我犯了错误。
在程序代码下面
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.DBCtrls,
Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Data.Win.ADODB;
type
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
DataSource1: TDataSource;
ADOQuery1: TADOQuery;
Panel1: TPanel;
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Label1: TLabel;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Memo1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
//проверим - есть ли текст в Memo. Если нет, выходим:
if Memo1.Text = '' then begin
ShowMessage('Вначале введите запрос!');
Memo1.SetFocus;
Exit;
end;
//текст есть. Очистим предыдущий запрос в наборе данных:
ADOQuery1.SQL.Clear;
//добавим новый запрос из Memo:
ADOQuery1.SQL.Add(Memo1.Text);
//открываем набор данных, т.е. выполняем запрос:
ADOQuery1.Open;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Clear;
end;
procedure TForm1.Memo1Change(Sender: TObject);
begin
ADOQuery1.SQL.Add(Memo1.Text);
ADOQuery1.SQL := Memo1.Lines;
end;
end.
答案 0 :(得分:2)
非常感谢所有试图帮助我的人!
在访问db中,JOIN必须在()中,因此该查询可以正常工作:
SELECT
company_name, date_of_order_start, date_of_order_finish, amount
FROM
(customers
INNER JOIN orders ON customers.id_customer=orders.id_customer)
INNER JOIN invoice ON invoice.id_order=orders.id_order
WHERE company_name='Ампер';
答案 1 :(得分:1)
我建议在查询周围添加错误处理:
Try
....
// setup and execute your query
except on e: exception do
begin
LogMyErrorSomehow(format('ERROR: [%s-%s] SQL:[%s]',
[e.ClassType.ClassName, e.Message, ADOQuery1.SQL.text]));
end;
end;
end;
答案 2 :(得分:1)
还有一个信息:在这里,你将Memo1.Text写入ADOQuery1.SQL两次
procedure TForm1.Memo1Change(Sender: TObject);
begin
ADOQuery1.SQL.Add(Memo1.Text); // <-- first time
ADOQuery1.SQL := Memo1.Lines; // <-- 2nd time
end;
您在此处将语句写入ADOQuery1:
//текст есть. Очистим предыдущий запрос в наборе данных:
ADOQuery1.SQL.Clear;
//добавим новый запрос из Memo:
ADOQuery1.SQL.Add(Memo1.Text);