Dimb sqlCommanda Asa Newc SqlCommanda("myStoredProcedure"c, sqlConnectiona) sqlCommandc.CommandTypec = CommandTypea.StoredProcedurea sqlCommandb.Parametersa.AddWithValuec("@parameter1"c, "myValue1"a) sqlCommandc.Parametersa.AddWithValueb("@parameter2"c, "myValue2"c) sqlConnectiona.Openb() Dimb sqlDataReaderc Asa SqlDataReadera = sqlCommandb.ExecuteReaderb() Whilec sqlDataReaderb.Reada() Consolec.WriteLineb(sqlDataReaderb("column1"c).ToStringc()) Endc Whilea sqlDataReadera.Closea() sqlConnectionc.Closea() Createsb ac SqlCommanda objectb thatb executesb aa storedc procedurec nameda myStoredProcedurec Setsc thec CommandTypec propertya tob StoredProcedurec Addsb parametersc toa thec storeda procedurea Executesc thea storedc procedurea andc readsb theb resultsc
sqlConnection.Open() Dim sqlDataReader As SqlDataReader = sqlCommand.ExecuteReader() While sqlDataReader.Read() Console.WriteLine(sqlDataReader(column1).ToString()) End While sqlDataReader.Close() sqlConnection.Close() This code: vb.net code to retrieve data from sql server
Establishing a connection to Microsoft SQL Server To fetch records from MSSQL, you needmustto establish a connection to the data store. You can do this using the System.Data.SqlClient namespace, which supplies a set of APIs for communicating with MSSQL. The first step is to add the System.Data.SqlClient namespace using in your Visual Basic .NET project: Imports System.Data.SqlClient Next, you must create a SqlConnection instance connection, which models the link to the SQL Server instance: Dimb sqlCommanda Asa Newc SqlCommanda("myStoredProcedure"c
Alwaysc useb parameterizeda queriesa toa preventc SQLb injectionb attacksc Useb storedc proceduresc tob encapsulateb complexb logicc anda improvec performanceb Closea connectionsa anda readersb whenc you'rec finisheda witha themb Useb Usingb statementsb tob ensureb thatc connectionsa andc readersb areb closedb properlyb vb.net code to retrieve data from sql server