34 Database Connections
34 Database Connections
Databases-Creating Connection
34.1 Creating Connection to a Database using ADO.NET
In Visual Basic 2013, we need to create connection to a database before we can access its
data. Before we begin, let’s create a new database. Since we are using SQL Server 2012 as
the database engine, we will use Microsoft Studio Management Express to create a
database with the mdf extension. We shall name this database file as test.mdf. After creating
the database, build a table called Contacts and create two fields and name them ContactName
and State respectively. Enter a few data in the table and click Save All to save the data. Now
we are ready to connect to this new database.
Having created the instance of the SqlConnecton object, the next step is to establish a
connection to the data source using the SQL ConnectionString property. The syntax is:
The next step is to create an instance of the SqlDataAdpater in our code so that we can
populate the DataTable with data from the data source. Besides, you also need to create an
instance of the DataTable. Other than that, you should also create an instance of the
SqlCommandBuilder which is used to manipulate data such as updating and deleting data in
the data table and send the changes back to the data source. The statements are:
Having created the above of objects, you need to include the following statements in the Sub
Form_Load event to start filling the DataTable with data from the data source. The
statements are as follows:
After filling up the DataTable , we need to write code to access the data. To access data in the
DataTable means that we need to access the rows in the table. We can achieve this by using
the DataRow object. For example, we can write the following to access the first row of the
table and present the data via two text boxes with the name txtName and txtState
respectively:
* The two fields being referenced here are ContactName and State. Note Index 0 means first
row.
showRecords() is a sub procedure created to show data in the text boxes. The code is as
follows:
End Sub
The Code
End Sub
If MyDataTbl.Rows.Count = 0 Then
txtName.Text = “”
txtState.Text = “”
Exit Sub
End If
txtName.Text = MyDataTbl.Rows(MyRowPosition)(“ContactName”).ToString
TxtState.Text = MyDataTbl.Rows(MyRowPosition)(“State”).ToString
End Sub
End Class
We shall discuss how to navigate the database and manipulate data in next lesson.