Writing a table with dates to sql database

10 ビュー (過去 30 日間)
Kevin Blackwell
Kevin Blackwell 2021 年 7 月 14 日
Using the database toolbox I'm haveing issues writing a table to my database that includes dates,
It works fine when the dates are converted to string using the cellstr function but these are not then registered as date values in my database and the column has to be set to text which then leads to issues on the sql side of things.
it there any way of exporting using database toolbox that allows me to keep the format of the date column ?
I've tried converting to a timetable but this isnt accepted by the database toolbox.

回答 (1 件)

MathWorks Computational Finance Team
MathWorks Computational Finance Team 2021 年 7 月 27 日
Hi Kevin,
I am not sure which MATLAB version or database you are working with. But, example I am sharing below assumes you are working with MATLAB R2021a:
% Connect to your database
conn = odbc(...); % For ODBC connection
% OR
conn = database(...); % For JDBC connection
% OR
conn = mysql(...); % For MySQL native connection
% OR
conn = postgresql(...); % For PostgreSQL native connection
% Read data from 'outages.csv'
outages = readtable('outages.csv');
% Use SQLWRITE to insert data into a outages database table.
% In this example the table does not exist in the database. SQLWRITE will create a new database table for you.
% Variables "OutageTime" & "RestoratonTime" in outages MATLAB table are of type datetime.
sqlwrite(conn,'outages',outages)
% Read the data back in MATLAB
opts = databaseImportOptions(conn,'outages');
opts = setoptions(opts,[2 5],'Type','datetime');
T = sqlread(conn,'outages',opts);
Hope this helps answer your question.
Thanks,
Rikin

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by