1、测试用表:
2、使用可视化工具Navicat在mysql数据库中创建一个函数,函数实现:输入id,返回对应的name:
CREATE FUNCTION getNameFunc(N int) RETURNS varchar(255)
BEGIN
#声明一个变量a_name
declare a_name varchar(255);
set a_name:=(select name from student where id = N);
return (a_name);
END
执行后,函数创建完成:
mysql中创建函数的语法在这里不做讲解,函数创建完成后,在Navicat可视化工具中对函数进行测试,保证函数没有问题?:
?创建函数过程中,如果出现报错信息如下:
1418 - This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)
则表示默认用户不得创建或修改函数,执行以下语句进行设置即可:
set global log_bin_trust_function_creators=1;
3、使用c++调用我们自己创建的函数,如下:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <mysql.h>
#include <chrono>
using namespace std;
using namespace chrono;
int main()
{
//1.初始化环境
MYSQL* mySql = mysql_init(NULL);
if (mySql == NULL)
{
printf("数据库环境初始化失败!\n");
return -1;
}
//Connect to server with option CLIENT_MULTI_STATEMENTS
mySql = mysql_real_connect(mySql, "localhost", "root", "root", "zzc", 3306, NULL, 0);
if (mySql == NULL)
{
printf("数据库连接失败!\n");
return -1;
}
mysql_set_character_set(mySql, "gbk");
char szSql[MAX_PATH] = { 0 };
sprintf(szSql, "select getNameFunc(%d)", 1001);
int status = mysql_real_query(mySql, szSql, strlen(szSql));
if (status)
{
printf("查询出错:%s\n", mysql_error(mySql));
}
else
{
MYSQL_RES * result = mysql_store_result(mySql);
if (result)
{
MYSQL_ROW m_row = nullptr;
m_row = mysql_fetch_row(result);
//提前已经知道只有一个数据
cout << string(m_row[0], mysql_fetch_lengths(result)[0]) << "\t";
mysql_free_result(result);
}
else
{
//调用mysql_field_count()来判定mysql_store_result()是否应生成非空结果集
if (0 == mysql_field_count(mySql))
{
printf("%lld 行被影响\n", mysql_affected_rows(mySql));
}
else
{
printf("发生错误:%s\n", mysql_error(mySql));
}
}
}
//释放资源-数据库
if (mySql)
{
mysql_close(mySql);
}
return 0;
}
?输出结果:
?
?
|