This seems like a basic scenario, but I can’t find relevant info anywhere.
I’m new to MySQL, coming from years of Microsoft SQL Server experience.
In MySQL, how do you convert a BINARY
or VARBINARY
value into a Base64 string, and vice-versa?
In Microsoft SQL Server, I’ve been using code like this:
CREATE FUNCTION [dbo].[convert_binary_base64] ( @input [VARBINARY] ( 3000 ) ) RETURNS [VARCHAR] ( 4000 ) AS BEGIN RETURN CAST ( '' AS [XML] ).value ( 'xs:base64Binary(sql:variable("@input"))' , 'VARCHAR(4000)' ) ; END GO
According to mysql.com
, it looks like the TO_BASE64
function only converts from text to text:
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_to-base64
As with the Microsoft SQL Server example above, is there an XML or JSON operation available in MySQL to perform this action?
Or can I force MySQL to “interpret” a VARBINARY
variable as text, and pass the text to TO_BASE64
?
(And if so, would that cause a performance degradation?)
Advertisement
Answer
To_BASE64 can also use VARCHAR as base and insert into varchar
DELIMITER // CREATE FUNCTION encodebase64( Inputtext VARBINARY(3000) ) RETURNS VARCHAR(4000) DETERMINISTIC BEGIN Return TO_BASE64(Inputtext); END // DELIMITER ;
So that
SELECT encodebase64('text');
returns
# encodebase64('text') dGV4dA==