Programming Blog

Simple but potentially useful – A collection of random programming stuffs

Archive for the ‘Database’ Category

How to connect to database using Visual Basic .NET

Posted by letmetutoryou on December 17, 2008

Hi everyone,  I have received many inquiries about how to connect to a database using .NET. I know the internet has zillions of sites with this code and one quick google searching might bring enough material to figure out this little issue. Well, so why are there people asking about it? I think the answer is the same, too much information, and each web page trying to be more complete than the last one.

For a beginner programmer all they need at the beginning is simplicity, to find basic and useful information. For the beginner, to be able of to win theirs first challenge sometimes is actually to decide to do keep or not in the programmer carreer. Let’s be simple. Below a complete code to connect,  insert and disconnect to a SQL Server database. I don’t want to explain the code jut to show up the correct sequence.

Dim thisConnection As SqlConnection

Dim strConnection As String

Dim nonqueryCommand As SqlCommand

Dim setsec As AppSettingsSection

strConnection = ConfigurationManager.ConnectionStrings(“ConnectionString1″).ToString() ‘ ConfigurationSettings.AppSettings(“ConnectionString1″)

thisConnection = New SqlConnection(strConnection)

‘Create Command object

nonqueryCommand = thisConnection.CreateCommand()

Try

‘ Open Connection

thisConnection.Open()

‘ Create INSERT statement with named parameters

nonqueryCommand.CommandText = “INSERT INTO email_list ( email_address ) VALUES ( @email_address )”

‘ Add Parameters to Command Parameters collection

nonqueryCommand.Parameters.Add(“@email_address”, SqlDbType.VarChar, 30)

‘ Prepare command for repeated execution

nonqueryCommand.Prepare()

nonqueryCommand.Parameters(“@email_address”).Value = Me.TextBoxemail.Text.ToString()

nonqueryCommand.ExecuteNonQuery()

Catch ex As SqlException

‘ Display error

Finally

‘ Close Connection

thisConnection.Close()

End Try

Posted in ADO, Database, Visual Basic | Tagged: , , , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.