Access to the database by the VB.net application is completed through ado.net. Ado. net uses the ODBC channel to access the database using SQL. Ado. Net's access to the database can be simply imagined as a three-layer processing model. The three layers and the main classes involved in each layer are as follows:
1. Create a connection to the database
2. Execute SQL statements through links
3. When data is available, process the data returned by the SQL statement.
Level |
Class Name |
Corresponding to the class name in the system. Data. oledb namespace |
Corresponding to the class name in the system. Data. sqlclient namespace |
1 |
Connection |
Oledbconnection |
Sqlconnection |
2 |
Dataadapter |
Oledbdataadapter |
Sqldataadapter |
Command |
Oledbcommand |
Sqlcommand |
3 |
Datareader |
Oledbdatareader |
Sqldatareader |
Dataset in system. Data |
Dataset |
Dataset |
Access different data sources can reference different namespaces, and then use the corresponding classes in ADO. net in the space. For example, access SQL server can use sqlconnection for link.
When we perform a link, we need to set the connectionstring attribute for the link, and use the name of the data source provider, such as sqlcnn. connectionstring = "Data Source = sqloledb; server = Dongzi/sqlexpress; uid = sa; Pwd = 123; database = machinoom"
Data Source = sqloledb in is the name of the SQL server data source provider on the. NET platform. In short, we need to find the name of the corresponding data source provider in. net when using different databases, and then set connectionstring.
The following uses sqlconnection, sqldataadapter, and other classes to create a demo to obtain the number of columns in the dbsturegister data table.
Imports system. Data
Imports system. Data. sqlclient
Public class form2
Private sub button#click (byval sender as system. Object, byval e as system. eventargs) handles button1.click
Dim sqlcnn as new sqlconnection
Dim sqglad as new sqldataadapter
Dim mydataset as new dataset
Dim tab as new datatable
Dim sqlcm as new sqlcommand
Sqlcnn. connectionstring = "Data Source = sqloledb; server = Dongzi/sqlexpress; uid = sa; Pwd = 123; database = machinoom"
Sqlcnn. open ()
Sqlcm. commandtext = "select * From dbsturegister"
Sqglad. selectcommand = sqlcm
Sqglad. selectcommand. Connection = sqlcnn
Sqglad. Fill (mydataset)
Tab = mydataset. Tables (0)
Txtcardno. Text = tab. Columns. Count
End sub
End Class
For the usage of dataadapter, see the online documentation of. net.
To learn about database access, you must be familiar with the applications and relationships of these three layers.