Insert Data into New Database Table Using Insert Functionality
To insert data into a new database table, you can use the sqlwrite
function. The datainsert
and fastinsert
functions will be removed in a future release. When using the
sqlwrite
function, you no longer have to preprocess or convert
the data, as required by the datainsert
function. The following short
examples show how to insert the same data using both the sqlwrite
and datainsert
functions. Use these examples for migrating to the
sqlwrite
function for data insertion.
Insert data in a new database table by using the sqlwrite
function.
% Read from patient.xls file patient_data = readtable('patient.xls'); % Insert using sqlwrite function sqlwrite(conn,'patient',patient_data);
Insert the same data by using the datainsert
function.
% Create a database table equivalent to data stored in patients.xls file sqlquery = ['CREATE TABLE patients(LastName varchar, Gender varchar, ' ... 'Age numeric, Location varchar, Height numeric, Weight numeric, ' ... 'Smoker Boolean, Systolic numeric, Diastolic numeric, ' ... 'SelfAssessedHealthStatus varchar)']; execute(conn,sqlquery) % Read from patients.csv file patient_data = readtable('patients.csv'); variablenames = patient_data.Properties.VariableNames; patient_data = table2cell(patient_data); % Convert to compatible data columns = size(patient_data,2); for i = 1:columns a = patient_data(:,i); if all(cellfun(@(x)isnumeric(x),a)) == true a(cellfun(@isnan,a)) = {Inf}; patient_data(:,i) = a; end end patient_data = cell2table(patient_data,'VariableNames',variablenames); % Insert using datainsert function datainsert(conn,'patient',variablenames,patient_data)
When using the datainsert
function, you must complete additional
steps to preprocess the data to insert. Use the sqlwrite
function
instead to avoid these extra steps.
See Also
sqlwrite
| readtable
| table2cell
| cell2table
| exec