mORMot的ORM有些略微不适合我的使用,故我希望直接手写SQL语句来操作数据库而不使用ORM。
需要使用的方法:
1 | function TSQLDBConnectionProperties.Execute(const aSql: RawUtf8; const Params: array of const; RowsVariant: PVariant = nil; ForceBlobAsNull: boolean = false): ISqlDBRows; |
具体用法见该方法定义区域处的注释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /// execute a SQL query, returning a statement interface instance to retrieve // the result rows corresponding to the supplied SELECT statement // - will call NewThreadSafeStatement method to retrieve a thread-safe // statement instance, then run the corresponding Execute() method // - raise an exception on error // - returns an ISqlDBRows to access any resulting rows (if ExpectResults is // TRUE), and provide basic garbage collection, as such: // ! procedure WriteFamily(const aName: RawUtf8); // ! var I: ISqlDBRows; // ! begin // ! I := MyConnProps.Execute('select * from table where name=?',[aName]); // ! while I.Step do // ! writeln(I['FirstName'],' ',DateToStr(I['BirthDate'])); // ! I.ReleaseRows; // ! end; // - if RowsVariant is set, you can use it to row column access via late // binding, as such: // ! procedure WriteFamily(const aName: RawUtf8); // ! var R: Variant; // ! begin // ! with MyConnProps.Execute('select * from table where name=?',[aName],@R) do // ! begin // ! while Step do // ! writeln(R.FirstName,' ',DateToStr(R.BirthDate)); // ! ReleaseRows; // ! end; // ! end; // - you can any BLOB field to be returned as null with the ForceBlobAsNull // optional parameter |
内容翻译到中文大致是这样的(本人英语水平较差,翻译结果可能会有些怪异,请酌情阅读)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /// 执行一个SQL语句, 返回一个语句接口实例用来读取 // 与所提供的 SELECT 语句对应的结果 // - 将会调用 NewThreadSafeStatement 方法以取得一个线程安全的 // 语句实例, 然后执行对应的 Execute() 方法 // - 发生错误时会抛出异常 // - 返回 ISqlDBRows 用来访问结果行 (若 ExpectResults 为 // TRUE), 并提供基本的垃圾回收, 示例: // ! procedure WriteFamily(const aName: RawUtf8); // ! var I: ISqlDBRows; // ! begin // ! I := MyConnProps.Execute('select * from table where name=?',[aName]); // ! while I.Step do // ! writeln(I['FirstName'],' ',DateToStr(I['BirthDate'])); // ! I.ReleaseRows; // ! end; // - 若 RowsVariant 已设置, 您可以使用它通过后期绑定进行行列访问 // 示例: // ! procedure WriteFamily(const aName: RawUtf8); // ! var R: Variant; // ! begin // ! with MyConnProps.Execute('select * from table where name=?',[aName],@R) do // ! begin // ! while Step do // ! writeln(R.FirstName,' ',DateToStr(R.BirthDate)); // ! ReleaseRows; // ! end; // ! end; // - 您可以使用 ForceBlobAsNull 将任何 BLOB 字段返回为 null // 可选参数(译者注:显而易见地,该参数默认值为false) |
注释中给出的示例大致时这样的:调用Execute方法来执行SQL语句,返回ISqlDBRows示例,每调用一次它的Step函数就会切换到下一行,把返回的行列表遍历完成后会返回false然后退出循环。
注释中有提到线程安全的问题。关于数据库客户端的多线程问题,可以参考这篇文章:https://synopse.info/forum/viewtopic.php?id=2684
发表回复