执行快速查询 - ExecuteScalar
函数简介
执行指定的SQL查询语句,并返回结果集中第一行的第一列的值。通常用于执行返回单个值的查询操作,例如 COUNT
、SUM
、MAX
等聚合函数。
函数原型
int ExecuteScalar(long ola, const long db, string sql);
参数定义
ola
(长整型数): OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。db
(长整型数): 数据库连接句柄,由 OpenDatabase 接口生成。sql
(字符串): 要执行的SQL查询语句。
返回值
- 返回值:查询结果中第一行第一列的值。如果查询失败或结果集为空,返回
0
。
示例
SDK
C#
using System;
using OLA.ServiceCenter.PlugFactory;
namespace OLADemo
{
internal class Program
{
static OLAPlugServer OLAServer;
static void Main(string[] args)
{
OLAServer = new OLAPlugServer();
var regResult = OLAServer.Reg(
OLAServer.UserCode,
OLAServer.SoftCode,
OLAServer.FeatureList
);
OLAServer.CreateCOLAPlugInterFace();
long db = OLAServer.OpenDatabase("OLAPlugDemo.db", "olaplug");
Console.WriteLine($"OpenDatabase 返回:{db}");
// 执行查询并返回第一行第一列的值
string sql = "SELECT COUNT(*) FROM MyTable";
int result = OLAServer.ExecuteScalar(db, sql);
Console.WriteLine($"查询结果: {result}");
}
}
}
Python
from OLAPlugServer import OLAPlugServer
# 实例化
OLAServer = OLAPlugServer()
# 注册
OLAServer.Reg(OLAServer.UserCode, OLAServer.SoftCode, OLAServer.FeatureList)
# 创建OLAPlug对象
OLAServer.CreateCOLAPlugInterFace()
# 打开数据库
db = OLAServer.OpenDatabase('OLAPlug.db', 'OLAPlug')
print(f"openDatabaseResult={db}")
# 执行查询并返回第一行第一列的值
sql = "SELECT COUNT(*) FROM MyTable"
result = OLAServer.ExecuteScalar(db, sql)
print(f"查询结果: {result}")
原生方式
Python
import os
import sys
from ctypes import *
# 1. 加载dll
# 此处路径为插件所在路径,请根据实际情况修改。
# 32位python使用x86版本,64位python使用x64版本
if sys.maxsize > 2**32:
olaplug_dll = WinDLL(os.path.abspath(os.path.join(os.getcwd(), 'OLAPlug_x64.dll')))
else:
olaplug_dll = WinDLL(os.path.abspath(os.path.join(os.getcwd(), 'OLAPlug_x86.dll')))
# 2. 注册到后台
UserCode = "c38e200f116d4fa8bd0deb45ccb523ea"
SoftCode = "701bc92ba84642c68845e7a06c10fd99"
FeatureList = "OLA|OLAPlus"
olaplug_dll.Reg.argtypes = [c_char_p, c_char_p, c_char_p]
olaplug_dll.Reg.restype = c_int32
result = olaplug_dll.Reg(UserCode.encode('utf-8'), SoftCode.encode('utf-8'), FeatureList.encode('utf-8'))
print(f'注册结果返回: {result}')
# 3. 创建ola对象
olaplug_dll.CreateCOLAPlugInterFace.restype = c_void_p
ola_obj = olaplug_dll.CreateCOLAPlugInterFace()
# 4. 打开数据库
olaplug_dll.OpenDatabase.argtypes = [c_void_p, c_char_p, c_char_p]
olaplug_dll.OpenDatabase.restype = c_void_p
db = olaplug_dll.OpenDatabase(ola_obj, "OLAPlugDemo.db".encode('utf-8'), "olaplug".encode('utf-8'))
print(f"openDatabaseResult={db}")
# 5. 执行查询并返回第一行第一列的值
sql = "SELECT COUNT(*) FROM MyTable"
olaplug_dll.ExecuteScalar.argtypes = [c_void_p, c_void_p, c_char_p]
olaplug_dll.ExecuteScalar.restype = c_int32
result = olaplug_dll.ExecuteScalar(ola_obj, db, sql.encode('utf-8'))
print(f"查询结果: {result}")
注意事项
- 该函数适用于执行返回单个值的查询操作,例如
COUNT
、SUM
、MAX
等聚合函数。 - 如果查询失败或结果集为空,函数将返回
0
。可以通过 GetDatabaseError 函数获取详细的错误信息。 - 确保传入的SQL查询语句语法正确,且表名和列名存在,否则可能导致查询失败。