Insert multiple numeric values in a single column to database using sqlwrite

4 ビュー (過去 30 日間)
Marek Mikula
Marek Mikula 2023 年 4 月 8 日
回答済み: Sandeep Mishra 2024 年 12 月 6 日
Hi, i want to insert multiple numeric values to database in one column is that possible because i only getting errors from matlab or is there any possibility to send whole cell array to one cell in database ?
  1 件のコメント
the cyclist
the cyclist 2023 年 4 月 8 日
What the database can store is solely determined by the database software. (You haven't told us what type of database.)
Forgetting about MATLAB for a moment ... are you able to write the SQL (I assume) statement that will do the insertion that you want? If not, you need to work on the SQL. If you can do that, then the next step is to see if you can write the equivalent insertion in MATLAB.
Most databases would not be able to store a MATLAB cell array, by default.

サインインしてコメントする。

回答 (1 件)

Sandeep Mishra
Sandeep Mishra 2024 年 12 月 6 日
Hi Marek,
When working with databases like SQLite in MATLAB, which often do not natively support storing arrays or complex data types, you can encode the integer array as a comma separated string value when inserting it into the database and decode it back into an array when retrieving it.
Refer to the following code snippet to encode and store the array:
% Create a table named 'people'
createTableSQL = ['CREATE TABLE people (id INTEGER PRIMARY KEY, ','name TEXT, value TEXT)'];
execute(conn, createTableSQL);
% Encoding array to Comma seperated string
arrayToInsert = [10,12];
concatString = char(strjoin(string(arrayToInsert), ','));
% Insert data into the table
insertDataSQL = ['INSERT INTO people (name, value) VALUES', sprintf('("Alice",''%s''), ("Charlie", ''%s'')', concatString, concatString)];
execute(conn, insertDataSQL);
To decode the string into array, you can use the following code snippet:
% Fetch all data from the 'people' table
fetchDataSQL = 'SELECT * FROM people';
data = fetch(conn, fetchDataSQL);
% Fetch Alice row values and decode string back to array
aliceRow = data(strcmp(data.name, 'Alice'), :);
pictureAliceStr = aliceRow.value{1};
values = str2double(split(pictureAliceStr , ','))
For more information, refer to the following MathWorks Documentation:
  1. strjoin’ function: https://www.mathworks.com/help/releases/R2024b/matlab/ref/strjoin.html
  2. str2double’ function: https://www.mathworks.com/help/releases/R2024b/matlab/ref/str2double.html
  3. split’ function: https://www.mathworks.com/help/releases/R2024b/matlab/ref/string.split.html
I hope this helps!

カテゴリ

Help Center および File ExchangeDatabase Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by