I just realized I added code on the blog for working with databases in C# but not for VB. This will be the missing post of one way in which you can use Visual Basic. Enjoy!
Imports System.Data
Imports System.Data.SqlClient
Dim cs As String = “Data Source=.\SQLEXPRESS;” + _
Dim cs As String = “Initial Catalog=NamesDB;” + _
Dim cs As String = “Integrated Security=True;”
Using con As New SqlConnection(cs)
con.Open()
‘ insert a record
sql = “INSERT INTO Names(Name) VALUES(@Name)”
Dim cmd1 As New SqlCommand(sql, con)
cmd1.Parameters.Add(“@Name”, SqlDbType.NVarChar, 100)
cmd1.Parameters(“@Name”).Value = “Bob”
cmd1.ExecuteNonQuery()
‘ insert a second record
cmd1.Parameters(“@Name”).Value = “David”
cmd1.ExecuteNonQuery()
‘ read records
sql = “SELECT * FROM Names”
Dim cmd2 As New SqlCommand(sql, con)
Using r As SqlDataReader = cmd2.ExecuteReader()
Dim iName As Integer = r.GetOrdinal(“Name”)
Do While r.Read()
If r.IsDbNull(iName) Then
Console.WriteLine(“Null”)
Else
Console.WriteLine(r.GetString(iName))
End If
Loop
End Using
‘ read a single value
sql = “SELECT TOP 1 Name FROM Names”
Dim cmd3 As New SqlCommand(sql, con)
Console.WriteLine(cmd3.ExecuteScalar())
End Using
(This post was done with the help of LearnVisualStudio.net. Thanks!)
In a future post I will be sure to add a post about how to use stored procedures! Hope this helps you. Have fun coding and as always, if there are any questions or suggestions, they are welcome. Thank you.