【发布时间】:2013-05-26 12:45:59
【问题描述】:
我正在尝试像这样进行多语句查询:
// without the second insert the query works fine.
// i need 2 querys to work because later, i'll do inserts on different kind of tables.
// that's why i need 2 querys, not a single query which insert 2 records.
with ZQuery1 do
begin
SQL.Clear;
SQL.Add('insert into client (name,age) values ('+QuotedStr('john')+','+QuotedStr('20')+');');
SQL.Add('insert into client (name,age) values ('+QuotedStr('doe')+','+QuotedStr('21')+');');
ExecSQL;
end;
我收到此错误消息:SQL 错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 2 行的“插入客户端(名称,年龄)值('doe','21')'附近使用正确的语法;
我已经查看了手册,组件 TZQuery 和 TZUpdateSql(来自 zeos lib)提供了在内部执行多个语句的可能性。
编辑[已解决]
谢谢 GregD,在运行了几次测试后,交易对我来说工作正常! 我就是这样用的,将来帮助别人。
try
ZConnection.AutoCommit := True;
ZConnection.StartTransaction;
With ZQuery Do
begin
SQL.Clear;
SQL.Add('insert into clients (name,age) values ('+QuotedStr('john')+','+QuotedStr('20')+')');
ExecSQL;
SQL.Clear;
SQL.Add('insert into clients (name,age) values ('+QuotedStr('doe')+','+QuotedStr('21')+')');
ExecSQL;
end;
ZConnection.Commit;
except
ZConnection.Rollback
end;
这就是 AutoCommit 属性在 Zeos 中的实际工作方式:
当 AutoCommit 为 True 时,事务会在每次执行 SQL 语句后自动提交,但您可以显式使用 StartTransaction 命令来防止这种自动提交,直到您显式调用 Commit。
AutoCommit 为 False 时,不应调用 StartTransaction。然后事务会自动启动,但不会在每条执行语句后自动提交。
过程 StartTransaction StartTransaction 过程在连接的数据库中启动一个新事务。它应该只在 AutoCommit 属性为 TRUE 时使用。每当您尝试在 AutoCommit 设置为 false 的情况下调用它时,都会引发 SInvalidOpInNonAutoCommit。这种行为是意料之中的,因为 StartTransaction 应该用作对 AutoCommit 模式的转义。当您调用 StartTransaction 时,AutoCommit 将“关闭”,然后,当您调用 Commit 或 Rollback 时,AutoCommit 再次“打开”。如果您将 AutoCommit 设置为 false,则会自动创建新事务,您可以选择关闭它们的方式(提交或回滚)。
过程提交将当前语句提交到数据库。仅应在非 AutoCommit 模式下使用(其中每个语句都是自动提交的,使此过程无用)或当您处于 AutoCommit 模式并希望完成由 StartTransaction 过程打开的事务时。提交完成当前事务,如果有的话。如果您不想将您的数据保存到数据库中,您应该使用回滚过程。
过程回滚回滚当前事务中的所有先前语句。仅应在非 AutoCommit 模式下使用(其中每个语句都是自动提交的,使此过程无用)或当您处于 AutoCommit 模式并希望完成由 StartTransaction 过程打开的事务时。回滚完成当前事务,如果有的话。如果您不想丢失您的状态,您应该使用 Commit 过程。
【问题讨论】:
-
OT:如果您拥有 Delphi 或 RAD Studio 的 Enterprise、Ultimate 或 Architect 版本,请尝试
FireDAC。 -
如果没有第二个插入,这是否有效?
-
是的,没有第二个插入它就像一个魅力:)
-
我一直想知道是谁发起了这种丑陋的
SQL.Clear; SQL.Add(...);模式而不是更短的SQL.Text := '...'。像所有愚蠢的东西一样,它非常耐用。
标签: mysql delphi delphi-xe3 zeos