Working with a Database in ASP.NET VB

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.

 

Working With a Database in C#

I do not use C# much. Here is some code I found while browsing the Internet that helps to connect to a database:

using System.Data;
using System.Data.SqlClient;
string cs = @"Data Source=.\SQLEXPRESS;" +
string cs = @"Initial Catalog=NamesDB;" +
string cs = @"Integrated Security=True;";
using (SqlConnection con = new SqlConnection(cs)) {
con.Open();
string sql = "INSERT INTO Names(Name) VALUES(@Name)";
// insert a record
SqlCommand cmd1 = 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";
SqlCommand cmd2 = new SqlCommand(sql, con);
using (SqlDataReader r = cmd2.ExecuteReader()) {
int iName = r.GetOrdinal("Name");
while (r.Read()) {
Console.WriteLine(
r.IsDBNull(iName)?"Null":r.GetString(iName)
);
}
}
// read a single value
sql = "SELECT TOP 1 Name FROM Names";
SqlCommand cmd3 = new SqlCommand(sql, con);
Console.WriteLine(cmd3.ExecuteScalar());
}

Good luck and Happy Coding!