How to insert and retrieve text with special characters from SQLite Matlab interface?
40 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Abel Szkalisity
am 3 Feb. 2020
Kommentiert: Abel Szkalisity
am 22 Jun. 2020
I have been struggling recently a lot with trying to insert and retrieve text from a database with SQLite connection with special characters as demonstrated with the code below (it should run as it is). The characters are all in the Unicode range 0-255.
Not only the characters are not correct upon retrieval from the database, even the number of them is different.
I suspect that the problem is somewhere during retrieval (i.e. fetch), as when I checked my db with an external program (DB Browser for SQLite) it showed the string correctly.
Could anyone correct the code below, or suggest how to do it otherwise?
Many thanks for your help in advance.
//Note: I'm sticking a bit to the SQLite interface instead of the JDBC driver. With JDBC connection this issue did not occur, however I'd like to access the database parallely, and the JDBC driver caused quite some issues there. //
%% Test database
% Set character encoding to UTF-8
slCharacterEncoding('UTF-8'); % I tried also without this, no effect
% Initialization
dbLocation = 'myTestDB.db';
rng(11950911);
% Check if the database needs to be created or simple connect to it
if ~exist(dbLocation,'file')
conn = sqlite(dbLocation,'create');
else
conn = sqlite(dbLocation);
end
% Creating a table named "Objects"
conn.exec('DROP TABLE IF EXISTS Objects;');
conn.exec(['CREATE TABLE Objects ( ' ...
'ObjectID INTEGER PRIMARY KEY, ' ...
'Data TEXT'...
');']);
% Creating test data
someTextWithWeirdChars = char((randi(255,1,100)));
% Create table from the input data for inserting
T = table({someTextWithWeirdChars},'VariableNames',{'Data'});
% Insert it into the Objects table
conn.insert('Objects',{'Data'},T);
% Fetching it back
result = conn.fetch('SELECT Data FROM Objects');
% In SQLite interface the result is a cellarray
resText = result{1};
if strcmp(resText,someTextWithWeirdChars)
disp('Yes, the text was correctly recovered.');
else
disp('No, something went wrong');
end
2 Kommentare
Christoph Schmid
am 30 Apr. 2020
Me too. Special characters are written correctly to the database but fetched incorrectly.
Furthermore fetching rows containing NULL values results in a error.
Akzeptierte Antwort
Christoph Schmid
am 19 Jun. 2020
I now use a workaround: mksqlite
Special characters are saved and retrieved correctly, NULL values are supported, BLOB data is saved and retrieved correctly (not so with the sqlite interface)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Database Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!