import data into matlab from database table -凯发k8网页登录
import data into matlab from database table
syntax
description
specifies additional options using one or more name-value arguments with any of the
previous input argument combinations. for example, specify data
= sqlread(___,name,value
)catalog =
"cat"
to import data from a database table stored in the
"cat"
catalog.
examples
import data from database table
use an odbc connection to import product data from a database table into matlab® using a microsoft® sql server® database. then, perform a simple data analysis.
create an odbc database connection to a microsoft sql server database with windows® authentication. specify a blank username and password. the database contains the table producttable
.
datasource = 'ms sql server auth'; conn = database(datasource,'','');
check the database connection. if the message
property is empty, then the connection is successful.
conn.message
ans = []
import data from the database table producttable
. the sqlread
function returns a matlab® table that contains the product data.
tablename = 'producttable';
data = sqlread(conn,tablename);
display the first five products.
head(data,5)
productnumber stocknumber suppliernumber unitcost productdescription _____________ ___________ ______________ ________ __________________ 9 1.2597e 05 1003 13 {'victorian doll'} 8 2.1257e 05 1001 5 {'train set' } 7 3.8912e 05 1007 16 {'engine kit' } 2 4.0031e 05 1002 9 {'painting set' } 4 4.0034e 05 1008 21 {'space cruiser' }
now, import the data using a row filter. the filter condition is that unitcost
must be less than 15.
rf = rowfilter("unitcost"); rf = rf.unitcost < 15; data = sqlread(conn,tablename,"rowfilter",rf);
again, display the first five products.
head(data,5)
productnumber stocknumber suppliernumber unitcost productdescription _____________ ___________ ______________ ________ ___________________ 9 1.2597e 05 1003 13 {'victorian doll' } 8 2.1257e 05 1001 5 {'train set' } 2 4.0031e 05 1002 9 {'painting set' } 1 4.0034e 05 1001 14 {'building blocks'} 5 4.0046e 05 1005 3 {'tin soldier' }
close the database connection.
close(conn)
import data from database table using import options
customize import options when importing data from a database table. control the import options by creating an sqlimportoptions
object. then, customize import options for different database columns. import data using the sqlread
function.
this example uses the patients.xls
file, which contains the columns gender
, location
, selfassessedhealthstatus
, and smoker
. the example also uses a microsoft® sql server® version 11.00.2100 database and the microsoft sql server driver 11.00.5058.
create a database connection to a microsoft sql server database with windows® authentication. specify a blank username and password.
datasource = 'ms sql server auth'; conn = database(datasource,'','');
load patient information into the matlab® workspace.
patients = readtable('patients.xls');
create the patients
database table using the patient information.
tablename = 'patients';
sqlwrite(conn,tablename,patients)
create an sqlimportoptions
object using the patients
database table and the databaseimportoptions
function.
opts = databaseimportoptions(conn,tablename)
opts = sqlimportoptions with properties: excludeduplicates: false variablenamingrule: 'modify' variablenames: {'lastname', 'gender', 'age' ... and 7 more} variabletypes: {'char', 'char', 'double' ... and 7 more} selectedvariablenames: {'lastname', 'gender', 'age' ... and 7 more} fillvalues: {'', '', nan ... and 7 more } rowfilter:variableoptions: show all 10 variableoptions
display the current import options for the variables selected in the selectedvariablenames
property of the sqlimportoptions
object.
vars = opts.selectedvariablenames; varopts = getoptions(opts,vars)
varopts = 1x10 sqlvariableimportoptions array with properties: variable options: (1) | (2) | (3) | (4) | (5) | (6) | (7) | (8) | (9) | (10) name: 'lastname' | 'gender' | 'age' | 'location' | 'height' | 'weight' | 'smoker' | 'systolic' | 'diastolic' | 'selfassessedhealthstatus' type: 'char' | 'char' | 'double' | 'char' | 'double' | 'double' | 'double' | 'double' | 'double' | 'char' missingrule: 'fill' | 'fill' | 'fill' | 'fill' | 'fill' | 'fill' | 'fill' | 'fill' | 'fill' | 'fill' fillvalue: '' | '' | nan | '' | nan | nan | nan | nan | nan | '' to access sub-properties of each variable, use getoptions
change the data types for the gender
, location
, selfassessedhealthstatus
, and smoker
variables using the setoptions
function. because the gender
, location
, and selfassessedhealthstatus
variables indicate a finite set of repeating values, change their data type to categorical
. because the smoker
variable stores the values 0
and 1
, change its data type to logical
. then, display the updated import options.
opts = setoptions(opts,{'gender','location','selfassessedhealthstatus'}, ... 'type','categorical'); opts = setoptions(opts,'smoker','type','logical'); varopts = getoptions(opts,{'gender','location','smoker', ... 'selfassessedhealthstatus'})
varopts = 1x4 sqlvariableimportoptions array with properties: variable options: (1) | (2) | (3) | (4) name: 'gender' | 'location' | 'smoker' | 'selfassessedhealthstatus' type: 'categorical' | 'categorical' | 'logical' | 'categorical' missingrule: 'fill' | 'fill' | 'fill' | 'fill' fillvalue:| | 0 | to access sub-properties of each variable, use getoptions
import the patients
database table using the sqlread
function, and display the last eight rows of the table.
data = sqlread(conn,tablename,opts); tail(data)
lastname gender age location height weight smoker systolic diastolic selfassessedhealthstatus _____________ ______ ___ _________________________ ______ ______ ______ ________ _________ ________________________ {'foster' } female 30 st. mary's medical center 70 124 false 130 91 fair {'gonzales' } male 48 county general hospital 71 174 false 123 79 good {'bryant' } female 48 county general hospital 66 134 false 129 73 excellent {'alexander'} male 25 county general hospital 69 171 true 128 99 good {'russell' } male 44 va hospital 69 188 true 124 92 good {'griffin' } male 49 county general hospital 70 186 false 119 74 fair {'diaz' } male 45 county general hospital 68 172 true 136 93 good {'hayes' } male 48 county general hospital 66 177 false 114 86 fair
display a summary of the imported data. the sqlread
function applies the import options to the variables in the imported data.
summary(data)
variables: lastname: 100×1 cell array of character vectors gender: 100×1 categorical values: female 53 male 47 age: 100×1 double values: min 25 median 39 max 50 location: 100×1 categorical values: county general hospital 39 st. mary s medical center 24 va hospital 37 height: 100×1 double values: min 60 median 67 max 72 weight: 100×1 double values: min 111 median 142.5 max 202 smoker: 100×1 logical values: true 34 false 66 systolic: 100×1 double values: min 109 median 122 max 138 diastolic: 100×1 double values: min 68 median 81.5 max 99 selfassessedhealthstatus: 100×1 categorical values: excellent 34 fair 15 good 40 poor 11
now set the filter condition to import only data for patients older than 40 years and not taller than 68 inches.
opts.rowfilter = opts.rowfilter.age > 40 & opts.rowfilter.height <= 68
opts = sqlimportoptions with properties: excludeduplicates: false variablenamingrule: 'modify' variablenames: {'lastname', 'gender', 'age' ... and 7 more} variabletypes: {'char', 'categorical', 'double' ... and 7 more} selectedvariablenames: {'lastname', 'gender', 'age' ... and 7 more} fillvalues: {'',, nan ... and 7 more } rowfilter: age > 40 & height <= 68 variableoptions: show all 10 variableoptions
again, import the patients
database table using the sqlread
function, and display a summary of the imported data.
data = sqlread(conn,tablename,opts); summary(data)
variables: lastname: 24×1 cell array of character vectors gender: 24×1 categorical values: female 17 male 7 age: 24×1 double values: min 41 median 45.5 max 50 location: 24×1 categorical values: county general hospital 13 st. mary s medical center 5 va hospital 6 height: 24×1 double values: min 62 median 66 max 68 weight: 24×1 double values: min 119 median 137 max 194 smoker: 24×1 logical values: true 8 false 16 systolic: 24×1 double values: min 114 median 121.5 max 138 diastolic: 24×1 double values: min 68 median 81.5 max 96 selfassessedhealthstatus: 24×1 categorical values: excellent 7 fair 3 good 10 poor 4
delete the patients
database table using the execute
function.
sqlquery = ['drop table ' tablename];
execute(conn,sqlquery)
close the database connection.
close(conn)
import data from database table in specific schema
use an odbc connection to import product data from a database table into matlab® using a microsoft® sql server® database. specify the schema where the database table is stored. then, sort and filter the rows in the imported data and perform a simple data analysis.
create an odbc database connection to a microsoft sql server database with windows® authentication. specify a blank user name and password. the database contains the table producttable
.
datasource = 'ms sql server auth'; conn = database(datasource,'','');
check the database connection. if the message
property is empty, then the connection is successful.
conn.message
ans = []
import data from the table producttable
. specify the database schema dbo
. the data
table contains the product data.
tablename = 'producttable'; data = sqlread(conn,tablename,'schema','dbo');
display the first few products.
data(1:3,:)
ans = 3×5 table productnumber stocknumber suppliernumber unitcost productdescription _____________ ___________ ______________ ________ __________________ 9 1.2597e 05 1003 13 'victorian doll' 8 2.1257e 05 1001 5 'train set' 7 3.8912e 05 1007 16 'engine kit'
display the first few product descriptions.
data.productdescription(1:3)
ans = 3×1 cell array {'victorian doll'} {'train set' } {'engine kit' }
sort the rows in data
by the product description column in alphabetical order.
column = 'productdescription';
data = sortrows(data,column);
display the first few product descriptions after sorting.
data.productdescription(1:3)
ans = 3×1 cell array {'building blocks'} {'convertible' } {'engine kit' }
close the database connection.
close(conn)
import specific number of rows from database table
use an odbc connection to import product data from a database table into matlab® using a microsoft® sql server® database. specify the maximum number of rows to import from the database table.
create an odbc database connection to a microsoft sql server database with windows® authentication. specify a blank user name and password. the database contains the table producttable
.
datasource = 'ms sql server auth'; conn = database(datasource,'','');
check the database connection. if the message
property is empty, then the connection is successful.
conn.message
ans = []
import data from the table producttable
. import only three rows of data from the database table. the data
table contains the product data.
tablename = 'producttable'; data = sqlread(conn,tablename,'maxrows',3)
data = 3×5 table productnumber stocknumber suppliernumber unitcost productdescription _____________ ___________ ______________ ________ __________________ 9 1.2597e 05 1003 13 'victorian doll' 8 2.1257e 05 1001 5 'train set' 7 3.8912e 05 1007 16 'engine kit'
close the database connection.
close(conn)
preserve variable names when importing data
import product data from a microsoft® sql server® database table into matlab® by using an odbc connection. the table contains a variable name with a non-ascii character. when importing data, preserve the names of all the variables.
create an odbc database connection to an sql server database with windows® authentication. specify a blank user name and password. the database contains the table producttable
.
datasource = "mssqlserverauth"; conn = database(datasource,"","");
check the database connection. if the message
property is empty, then the connection is successful.
conn.message
ans = []
add a column to the database table producttable
. the column name contains a non-ascii character.
sqlquery = "alter table producttable add tamaño varchar(30)";
execute(conn,sqlquery)
import data from the database table producttable
. the sqlread
function returns a matlab table that contains the product data. display the first three rows of the data in the table.
tablename = "producttable";
data = sqlread(conn,tablename);
head(data,3)
ans=3×6 table
productnumber stocknumber suppliernumber unitcost productdescription tama_o
_____________ ___________ ______________ ________ __________________ __________
9 1.2597e 05 1003 13 {'victorian doll'} {0×0 char}
8 2.1257e 05 1001 5 {'train set' } {0×0 char}
7 3.8912e 05 1007 16 {'engine kit' } {0×0 char}
the sqlread
function converts the name of the new variable into ascii characters.
preserve the name of the variable that contains the non-ascii character by specifying the variablenamingrule
name-value pair argument. import the data again.
data = sqlread(conn,tablename, ... 'variablenamingrule',"preserve"); head(data,3)
ans=3×6 table
productnumber stocknumber suppliernumber unitcost productdescription tamaño
_____________ ___________ ______________ ________ __________________ __________
9 1.2597e 05 1003 13 {'victorian doll'} {0×0 char}
8 2.1257e 05 1001 5 {'train set' } {0×0 char}
7 3.8912e 05 1007 16 {'engine kit' } {0×0 char}
the sqlread
function preserves the non-ascii character in the variable name.
close the database connection.
close(conn)
retrieve metadata information about imported data
retrieve metadata information when importing data from a database table. import data using the sqlread
function and explore the metadata information by using dot notation.
this example uses the outages.csv
file, which contains outage data. also, the example uses a microsoft® sql server® version 11.00.2100 database and the microsoft sql server driver 11.00.5058.
create a database connection to a microsoft sql server database with windows® authentication. specify a blank user name and password.
datasource = "ms sql server auth"; conn = database(datasource,"","");
load outage information into the matlab® workspace.
outages = readtable("outages.csv");
create the outages
database table using the outage information.
tablename = "outages";
sqlwrite(conn,tablename,outages)
import the data into the matlab workspace and return metadata information about the imported data.
[data,metadata] = sqlread(conn,tablename);
view the names of the variables in the imported data.
metadata.properties.rownames
ans = 6×1 cell array
{'region' }
{'outagetime' }
{'loss' }
{'customers' }
{'restorationtime'}
{'cause' }
view the data type of each variable in the imported data.
metadata.variabletype
ans = 6×1 cell array
{'char' }
{'char' }
{'double'}
{'double'}
{'char' }
{'char' }
view the missing data value for each variable in the imported data.
metadata.fillvalue
ans = 6×1 cell array
{0×0 char}
{0×0 char}
{[ nan]}
{[ nan]}
{0×0 char}
{0×0 char}
view the indices of the missing data for each variable in the imported data.
metadata.missingrows
ans = 6×1 cell array
{ 0×1 double}
{ 0×1 double}
{604×1 double}
{328×1 double}
{ 29×1 double}
{ 0×1 double}
display the first eight rows of the imported data that contain missing restoration time. data
contains restoration time in the fifth variable. use the numeric indices to find the rows with missing data.
index = metadata.missingrows{5,1}; nullrestoration = data(index,:); head(nullrestoration)
ans=8×6 table
region outagetime loss customers restorationtime cause
___________ _________________________ ______ __________ _______________ __________________
'southeast' '2003-01-23 00:49:00.000' 530.14 2.1204e 05 '' 'winter storm'
'northeast' '2004-09-18 05:54:00.000' 0 0 '' 'equipment fault'
'midwest' '2002-04-20 16:46:00.000' 23141 nan '' 'unknown'
'northeast' '2004-09-16 19:42:00.000' 4718 nan '' 'unknown'
'southeast' '2005-09-14 15:45:00.000' 1839.2 3.4144e 05 '' 'severe storm'
'southeast' '2004-08-17 17:34:00.000' 624.1 1.7879e 05 '' 'severe storm'
'southeast' '2006-01-28 23:13:00.000' 498.78 nan '' 'energy emergency'
'west' '2003-06-20 18:22:00.000' 0 0 '' 'energy emergency'
delete the outages
database table using the execute
function.
sqlstr = "drop table ";
sqlquery = strcat(sqlstr,tablename);
execute(conn,sqlquery)
close the database connection.
close(conn)
input arguments
conn
— database connection
connection
object
database connection, specified as an odbc object or jdbc object created using the function.
tablename
— database table name
string scalar | character vector
database table name, specified as a string scalar or character vector denoting the name of a table in the database.
example: "employees"
data types: string
| char
opts
— database import options
sqlimportoptions
object
database import options, specified as an object.
name-value arguments
specify optional pairs of arguments as
name1=value1,...,namen=valuen
, where name
is
the argument name and value
is the corresponding value.
name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
before r2021a, use commas to separate each name and value, and enclose
name
in quotes.
example: data =
sqlread(conn,'inventorytable','catalog','toy_store','schema','dbo','maxrows',5)
imports five rows of data from the database table inventorytable
stored in the toy_store
catalog and the dbo
schema.
catalog
— database catalog name
string scalar | character vector
database catalog name, specified as a string scalar or character vector. a catalog serves as the container for the schemas in a database and contains related metadata information. a database can have multiple catalogs.
example: catalog = "toy_store"
data types: string
| char
schema
— database schema name
string scalar | character vector
database schema name, specified as a string scalar or character vector. a schema defines the database tables, views, relationships among tables, and other elements. a database catalog can have numerous schemas.
example: schema = "dbo"
data types: string
| char
maxrows
— maximum number of rows to return
positive numeric scalar
maximum number of rows to return, specified as the comma-separated pair consisting of
'maxrows'
and a positive numeric scalar. by default, the
sqlread
function returns all rows from the executed sql
query. use this name-value pair argument to limit the number of rows imported into
matlab.
example: 'maxrows',10
data types: double
variablenamingrule
— variable naming rule
"modify"
(default) | "preserve"
variable naming rule, specified as the comma-separated pair consisting of 'variablenamingrule'
and one of these values:
"modify"
— remove non-ascii characters from variable names when thesqlread
function imports data."preserve"
— preserve most variable names when thesqlread
function imports data. for details, see the limitations section.
example: 'variablenamingrule',"modify"
data types: string
rowfilter
— row filter condition
(default) | matlab.io.rowfilter
object
row filter condition, specified as a
matlab.io.rowfilter
object.
example: rf = rowfilter("productnumber"); rf =
rf.productnumber <= 5;
sqlread(conn,tablename,"rowfilter",rf)
output arguments
data
— imported data
table
imported data, returned as a table. the rows of the table correspond to
the rows in the database table tablename
. the variables
in the table correspond to each column in the database table. for columns
that have numeric
data types in the database table, the
variable data types in data
are double
by default. for columns that have text, date
,
time
, or timestamp
data types in
the database table, the variable data types are cell arrays of character
vectors by default.
if the database table contains no data to import, then
data
is an empty table.
metadata
— metadata information
table
metadata information, returned as a table with these variables.
variable name | variable description | variable data type |
---|---|---|
| data type of each variable in the imported data | cell array of character vectors |
| value of missing data for each variable in the imported data | cell array of missing data values |
| indices for each occurrence of missing data in each variable of the imported data | cell array of numeric indices |
by default, the sqlread
function imports text
data as a character vector and numeric data as a double.
fillvalue
is an empty character
array (for text data) or nan
(for numeric
data) by default. to change the missing data value to another
value, use the object.
the rownames
property of the metadata
table contains
the names of the variables in the imported data.
limitations
the
sqlread
function returns an error when you use thevariablenamingrule
name-value argument with the objectopts
.when the
variablenamingrule
name-value pair argument is set to the value"modify"
:the variable names
properties
,rownames
, andvariablenames
are reserved identifiers for thetable
data type.the length of each variable name must be less than the number returned by .
the
sqlread
function returns an error if you specify therowfilter
name-value argument with thesqlimportoptions
objectopts
. it is ambiguous which of therowfilter
object to use in this case, especially if the filter conditions are different.
version history
introduced in r2018ar2023a: selectively import rows of data based on filter condition
you can use the rowfilter
name-value argument to selectively
import rows of data from a database table.
see also
functions
- | | | | | | | | | | | |
topics
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)