Run a command on an sql database in VB.Net

July 14, 2010 - 05:48

Connecting to a microsoft sql database is done by first creating the database on your server and assigning the correct username and password. Once this is done then create your connection string. This will look something like this:

server=127.0.0.1;database=dbname;uid=username;pwd=password;


Make sure to replace the dbname,username and password with your correct details.

I would normally add this as a string into the web.config file as if this is hard coded into all the webpages, any change requires a large search and replace.

Once you have the connection string then you need to make sure you have created the necessary stored procedure on your sql server. In the example we have a stored procedure called spContactLogin passing the variables Email and Password.

<%@ Import Namespace="System.Data.SqlClient,System.Data" %>

dim server_connection as string = "server=127.0.0.1;database=dbname;uid=username;pwd=password;"
Dim myConnection As New sqlconnection(server_connection)
Dim mycommand As new sqlcommand
mycommand.connection = myconnection
mycommand.Commandtype = CommandType.storedprocedure
mycommand.CommandText = "spContactLogin"
mycommand.parameters.add("@Email",email)
mycommand.parameters.add("@PasswordText",passwordtext)
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()



This then connects to the database and runs the sqlcommand, be sure to remember to close the connection after the ExecuteNonQuery() command.



© 2011 simplevb.net