Untitled
unknown
c_cpp
10 months ago
1.8 kB
14
Indexable
#include <iostream>
#include "sqlite3.h"
// Функция square(x): возвращает квадрат числа
static void squareFunc(sqlite3_context* ctx, int argc, sqlite3_value** argv) {
if (argc == 1) {
if (sqlite3_value_type(argv[0]) == SQLITE_INTEGER) {
int x = sqlite3_value_int(argv[0]);
sqlite3_result_int(ctx, x * x);
}
else if (sqlite3_value_type(argv[0]) == SQLITE_FLOAT) {
double x = sqlite3_value_double(argv[0]);
sqlite3_result_double(ctx, x * x);
}
else {
sqlite3_result_null(ctx);
}
}
else {
sqlite3_result_null(ctx);
}
}
int main() {
sqlite3* db;
char* errMsg = nullptr;
// Открываем БД в памяти
if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
std::cerr << "Ошибка открытия БД\n";
return 1;
}
// Регистрируем функцию square
sqlite3_create_function(db, "square", 1, SQLITE_UTF8, nullptr, squareFunc, nullptr, nullptr);
// Пример запроса
const char* sql = "SELECT square(5), square(3.5), square(NULL);";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
std::cout << "square(5) = " << sqlite3_column_int(stmt, 0) << "\n";
std::cout << "square(3.5) = " << sqlite3_column_double(stmt, 1) << "\n";
if (sqlite3_column_type(stmt, 2) == SQLITE_NULL)
std::cout << "square(NULL) = NULL\n";
}
}
else {
std::cerr << "Ошибка выполнения запроса\n";
}
sqlite3_finalize(stmt);
sqlite3_close(db);
}
Editor is loading...
Leave a Comment